0

I want to call some functions but I don't know how to import the package. I tried like follows but it failed. How can I do? (I want to use some third-party package to analyzing each doc, the code below is just a test)

Please, if you know the answer...

import couchdb as db
import datetime

couch = db.Server()

d1 = couch['test']

def map(doc):
    text = doc['text']
    ti = doc['timestamp_ms']
    ti = ti[:10] + '.' + ti[10:]
    dateArray = datetime.datetime.utcfromtimestamp(float(time))
    if (dateArray.time().hour < 12):
            yield ["am"], text
    else:
            yield ["pm"], text

for row in d1.query(map, descending=True, language='python'):
        print row.key, row.value
coDe murDerer
  • 1,858
  • 4
  • 20
  • 28
Jo Yang
  • 1
  • 2

1 Answers1

0

You can use datetime inside a map function only if you import datetime inside the map function. So your example would look like -


    def map(doc):
        text = doc['text']
        ti = doc['timestamp_ms']
        ti = ti[:10] + '.' + ti[10:]
        from datetime import datetime
        dateArray = datetime.utcfromtimestamp(float(time))
        if (dateArray.time().hour 

However, you cannot load third-party libraries in the map function. I tried importing the nose test library and saw this in couch logs -

    [[{initial_call,
       {couch_os_process,init,['Argument__1']}},
      {pid,<0.14643.4>},
      {registered_name,[]},
      {error_info,
       {exit,
        {function_clause,
         [{couch_os_process,handle_info,
           [{#Port<0.13927>,
             {data,
              {eol,
               <<"{\"log\": \"Traceback (most recent call last):\n  File \\"/usr/local/lib/python2.7/dist-packages/couchdb/view.py\\", line 79, in map_doc\n    results.append([[key, value] for key, value in function(doc)])\n  File \\"\\", line 5, in map\nImportError: No module named nose\n\"}">>}}},
            {os_proc,"couchpy",#Port<0.13927>,
             #Fun,
             #Fun,5000}]},
          {gen_server,handle_msg,5},
          {proc_lib,init_p_do_apply,3}]},
        [{gen_server,terminate,6},
         {proc_lib,init_p_do_apply,3}]}},

You might be able to if you install the third party library directly on your host python installation, not in your virtual environment. However, I do not recommend this practice. Use a virtual env instead always.

Gavin
  • 349
  • 4
  • 10