EzDevInfo.com

eve

Python REST API for Humans™ Python REST API Framework — Eve 0.6-dev0 documentation

submit request (post) internally in python-eve

I have a resource in eve e.g. ABC, I want to manipulate another resource e.g. BCD when some condition meet while I am posting a new item to ABC, I know I can hook the event for post/pre_POST_ABC but is there a 'internal' way to do post on BCD without going through via the HTTP again?


Source: (StackOverflow)

Serve static files with Eve

I am running Flask and Eve on localhost at a same time. The Flask app serves static files and makes requests to the Eve app to get some data. I want to run Eve only, without a separate Flask app. How can I serve static files with Eve?


Source: (StackOverflow)

Advertisements

EVE - define custom flask controllers [closed]

I'm using EVE for couple of days to create my own REST API but I want to have custom Flask Controller integrated with EVE is there any possibility to do this? Thanks.


Source: (StackOverflow)

ConnectionException connecting a Eve REST API to a MongoDB instance

[What is Eve?]

I just installed the 'eve demo' I can't get it to start working.

The error is:

eve.io.base.ConnectionException: Error initializing the driver. Make sure the database serveris running. Driver exception: OperationFailure(u"command SON([('authenticate', 1), ('user', u'user'), ('nonce', u'cec66353cb35b6f5'), ('key', u'14817e596653376514b76248055e1d4f')]) failed: auth fails",)

I have mongoDB running, and I have installed Eve and Python2.7.

I create the run.py and the settings.py required.

What is not working ? am I missing something ?


Source: (StackOverflow)

How to add some self process when using Python eve?

How to add some self process when using Python eve ?

For example, this is my activity schema.

schema = {
        'id': {
            'type': 'integer',
            'readonly': True,
            'unique': True,
        },

        'name': {
            'type': 'string',
            'minlength': 3,
            'maxlength': 20,
            'required': True,
        },

        'date': {
            'type': 'datetime',
        },

        'location': {
            'type': 'string',
        },

        'icon': {
            'type': 'media',
        },

        'type': {
            'type': 'integer',
            'allowed': [i for i in range(5)],
        },

        'info': {
            'type': 'list',
        },

        'share': {
            'type': 'dict',
            'readonly': True,
            'schema': {
                'url': {
                    'type': 'string',
                },
                'qr': {
                    'type': 'media',
                }
            }
        },
        'publisher': {
            'type': 'list',
        },
        'participators': {
            'type': 'list',
        },
     }

And I want to generate a share url and qr-code when the activity is creatd using POST, and give it a simple ID like 001, I have achieve the code to generate something like qr-code generator, but I don't how to add all these function after info to be POSTed and before being saved to MongoDB.

I have seen something like Event Hook, but I still didn't know how to achieve that like fixing the POST data or some other func.

Can u just show me some datail example, thank you so much.


Source: (StackOverflow)

Using MongoDB and Eve to rapidly develop an iOS Prototype?

I'm currently planning a new project which involves a few Proof of Concept prototypes for testing before a real application will grow from it. The application will be mainly a iOS Application which communicates with a Database on a remote server over a WebService, so pretty basic stuff here.

As it always takes me a long time to configure the SQL Database and write the Application for the Server (RESTful API) I started to read through the possibilities of NoSQL Databases and their prebuilt possibilities to communicate/sync with a remote server. Which would clearly reduce the work needed for the Server part as far as my understanding of these things goes.

Now I started to read through MongoDB in addition with Eve (Python) which expands the HTTP REST API which MongoDB offers. As their RESTful API offers everything needed for a testing prototype I came to ask myself why I should even write my own REST API if I can get everything I need from Eve's API ?

What are the downsides of using Eve and MongoDB? What are the benefits to write my own RESTful API around my MongoDB Instance?!


Source: (StackOverflow)

You don't have the permission to access the requested resource in Python Eve

When hitting the REST endpoint with DELETE (http://localhost:5000/tax/559c0180b9f1f1072f240065), I receive an error. The error was as follows. Tax is the collection I'm attempting to delete and the following value in the URL is the id of the document I'd like deleted. Status 403 FORBIDDEN Show explanation Loading time: 7 Request headers Accept: application/json Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo CSP: active User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36 Content-Type: application/x-www-form-urlencoded Accept-Encoding: gzip, deflate, sdch Accept-Language: en-US,en;q=0.8 Response headers Content-Type: application/json Content-Length: 180 Server: Eve/0.6-dev0 Werkzeug/0.10.4 Python/2.7.6 Date: Tue, 07 Jul 2015 16:46:40 GMT

{ _status: "ERR" _error: { message: "You don't have the permission to access the requested resource. It is either read-protected or not readable by the server." code: 403 }- } The payload I used was {"KONG": "Donkey"}

What can I do to resolve this issue?

The code I used is at the following links

https://gist.github.com/anonymous/fda6080f3e7910d4be84 https://gist.github.com/anonymous/3bab73901f901087177b


Source: (StackOverflow)

Python Sql Alchemy - How to jsonify a class object result from a database query

Basically, I just want to json encode the results of my sql query.

x = db.session.query(User).filter_by(username = request.form['username'], password = request.form['password']).first()
  print vars(x)
return jsonify(x)

raise TypeError(repr(o) + " is not JSON serializable")

TypeError: < User WashingtonGeorge> is not JSON serializable

Here is the result for the print vars(x)

{'_updated': None, 'username': u'WashingtonGeorge', 'password': u'Washington', '_sa_instance_state': <sqlalchemy.orm.state.InstanceState object at 0x7fd12a50c8d0>, 'firstname': u'George', 'lastname': u'Washington', '_created': None, 'fullname': u'George Washington', '_id': 1, 'email': u'WashingtonGeorge@yahoo.com'}

Source: (StackOverflow)

Requesting list of embedded objects

I have items endpoint which contains a list of embedded images. The scheme looks like:

_schema = {
    'name': required_string,  # group name
    'description': {
        'type': 'string',
        'maxlength': 140,
    },
    'images': {
        'type': 'list',
        'scheme': {
            'type': 'objectid',
            'data_relation': {
                'resource': 'images',
                'embeddable': True,
                'field': '_id',
            }
        },
    }
}

So I'm trying to make a request to the items endpoint to get embedded objects

/items/549ae47f4fb9041305403292?embedded={"images":1}

But instead of embedded images I receive just the regular object with the list of images _ids.

Here is an example of object:

{
    "_updated": "Wed, 24 Dec 2014 16:06:23 GMT",
    "name": "New Item",
    "images": [
        "549ae47f4fb904130540328b",
        "549ae47f4fb904130540328e",
        "549ae47f4fb9041305403291"
    ],
    "_created": "Wed, 24 Dec 2014 16:06:23 GMT",
    "_id": "549ae47f4fb9041305403292",
    "_etag": "949e3b731823bb2c08682ba4b6696b86856ef941",
    "description": "The best item ever"
}

I tried to convert images ids in list to objectids, but it doesn't help. Any ideas why it doesn't work? Thanks


Source: (StackOverflow)

Using Eve's DB layer without HTTP

In my application, the MongoDB collections need to be updated by a server-side script job (IE: a cron job that scrapes/pulls from other APIs every 30minutes). What I really want to do is make updates to the MongoDB collections, but have the data be validated against the schema and include metadata (updated, created, etc).

The two ways that come to mind to solve this is:

  1. Have a fake client to do HTTP POST/PUT/PATCHES. However, this means this fake client would have to deal with things like authentication/authorization/last-modified-since.
  2. Use PyMongo to interact with the DB directly. However, this means I wouldn't have the data validation, or the metadata stored.

Does Eve have hooks for the database so that I can do Eve-rich database updates without HTTP?


Source: (StackOverflow)

Angularjs + Python Eve Token based authentication

I am currently implementing a auth APIs for python EVE.

There are quite a few projects around token based auth in Angularjs notably https://github.com/sahat/satellizer

My question is, How could I integrate satellizer with Python Eve?


Source: (StackOverflow)

filename always null when post new media file

Always when I post a new media file the filename fildset in mongo is become null.

I've used curl, postman and python requests library but always result is the same :(

The definition in the settings.py are:

EXTENDED_MEDIA_INFO = ['content_type', 'name', 'length']

(I've tried with "filename" too)

And the definition:

files = { 
    'item_title': 'file',
    'auth_field': 'account_id',
    'schema': {
        'title': {
            'type': 'string',
            },  
        'account_id': {
            'type': 'objectid',
            'required': True,
            'data_relation': {
                'resource': 'accounts',
                'field': '_id',
                }   
            },  
        'file': {
            'type': 'media',
            'required': True,
            },  
        'tags': {
            'type': 'list',
            'schema': {
                'type': 'string',
                },  
            },

        }   
    }

When I use curl as in your web example:

curl -F "account_id=553a0b0f8a6f501695fa8b42" -F "file=@blua.jpg" http://localhost:5000/files

{"_updated": "Thu, 30 Apr 2015 21:47:51 GMT", "_links": {"self": {"href": "files/5542a3078a6f5064a3a04dba", "title": "file"}}, "_created": "Thu, 30 Apr 2015 21:47:51 GMT", "_status": "OK", "_id": "5542a3078a6f5064a3a04dba", "_etag": "90314f9491a92dc84aa90880d69e2b76bfd947db"}

In mongo is stored:

> db.fs.files.find({}).pretty()
{
    "_id" : ObjectId("5542a54f8a6f5064a3a04dbb"),
    "contentType" : "image/jpeg",
    "chunkSize" : 261120,
    "filename" : null,                   <-------------------- THE PROBLEM
    "length" : 437658,
    "uploadDate" : ISODate("2015-04-30T21:57:35.080Z"),
    "md5" : "90dce7915217108434acd61b3285d907"
}
> db.files.find({}).pretty()
{
    "_id" : ObjectId("5542a54f8a6f5064a3a04dbe"),
    "_updated" : ISODate("2015-04-30T21:57:35Z"),
    "account_id" : ObjectId("553a0b0f8a6f501695fa8b42"),
    "file" : ObjectId("5542a54f8a6f5064a3a04dbb"),
    "_created" : ISODate("2015-04-30T21:57:35Z"),
    "_etag" : "466ab27d09d6eb87d2c0ab5f094875011e72cca2"
}

Using requets python [http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file]:

def file_post(token, account_id, filename, content, mimetype, debug=True):
  path = __path__
  url = Bkend.url(path)
  headers = {'Authorization': Rest.authorization(token)}

  payload = {'account_id': account_id}

  resp = requests.post(
      url=url,
      headers=headers,
      data=payload,
      files={'file': (secure_filename(filename), content, mimetype)}
     #files={'file': ('filename', content, mimetype)}
     #files={'file': content}
      )

  if debug:
      log = "\n - Url: " + str(url) + \ 
          "\n - Headers:" + str(headers) + \ 
          "\n - Payload/Params:" + json.dumps(payload) + \ 
          "\n\n...............................\n" + \ 
          "\n - Resp Status Code: " + str(resp.status_code) + \ 
          "\n - Resp URL: " + str(resp.url) + \ 
          "\n - Resp Headers: " + str(resp.headers) + \ 
          "\n - Resp Avg: " + str(resp.elapsed) + \ 
          "\n - Resp Body: \n" + resp.text
      capp.logger.debug(log)
  return resp

I've even tested to set the filename, content_type and headers explicitly, but always get the same result

> db.files.find({}).pretty()
{
    "_id" : ObjectId("5542a86c8a6f5064a3a04dce"),
    "_updated" : ISODate("2015-04-30T22:10:52Z"),
    "account_id" : ObjectId("553a0b0f8a6f501695fa8b42"),
    "file" : ObjectId("5542a86c8a6f5064a3a04dbf"),
    "_created" : ISODate("2015-04-30T22:10:52Z"),
    "_etag" : "d5a203b20dc75a8ae8691cd8cfecb627da9a181b",
    "tags" : [
        "STOP",
        "BUS",
        "MELON"
     ],
    "title" : "The bus stop" 
}
> db.fs.files.find({}).pretty()
{
    "_id" : ObjectId("5542a86c8a6f5064a3a04dbf"),
    "contentType" : "application/pdf",
    "chunkSize" : 261120,
    "filename" : null,         <-------------- THE PROBLEM
    "length" : 3589703,
    "uploadDate" : ISODate("2015-04-30T22:10:52.507Z"),
    "md5" : "f2176c1780b32b549ca7513893254c06"
}
> 

With Postman: screenshot - 010515 - 00 19 43

The result in mongo with the same end:

> db.files.find({}).pretty()
{
    "_id" : ObjectId("5542aa768a6f5064a3a04de1"),
    "_updated" : ISODate("2015-04-30T22:19:34Z"),
    "account_id" : ObjectId("553a0b0f8a6f501695fa8b42"),
    "file" : ObjectId("5542aa768a6f5064a3a04ddf"),
    "_created" : ISODate("2015-04-30T22:19:34Z"),
    "_etag" : "d6a3ba5ad5f6fb7ef6557000841194501815e39a"
}
> db.fs.files.find({}).pretty()
{
    "_id" : ObjectId("5542aa768a6f5064a3a04ddf"),
    "contentType" : "application/pdf",
    "chunkSize" : 261120,
    "filename" : null,      <------ The problem again
    "length" : 16651,
    "uploadDate" : ISODate("2015-04-30T22:19:34.269Z"),
    "md5" : "20ef57d98d4bc11ab55a260a4d75b727"
}
> 

Any idea? is a bug or I'am doing something wrong?

Solved fails in versión 0.5.3 and is fixed in version 0.5.4


Source: (StackOverflow)

Can't reach Eve REST API

I'm using Eve to create a REST API for MongoDB. It's all working fine, except for the fact that I can't reach the API from any other computer (in the same network), or even a different URL (e.g.: if I set SERVER_NAME = 'localhost:29000', I will not be able to reach the API with 127.0.0.1 and vice versa).

I've been looking around for hours, and I can't seem to find an answer. I also tried other REST API's for MongoDB like Kule, and they seem to work just fine, but they don't have as many options as Eve has.


Source: (StackOverflow)

How to add to a list type in Python Eve without replacing old values

I have a very similar setup to the person in this question: How do I update a list data_relation in Python Eve with a users resource and a friends sub-resource of list type.

users = {
    …
    ‘friends’: {
    'type': 'list’, 
        'schema': {
        'type': 'objectid’, 
        'data_relation': { 
            'resource': 'users’ 
        } 
    }
 }
},

However, when I try to add a new value to the friends list, the other values in the list get replaced by the new value. How do I add a single value to the list and keep the old values?

GET /users/5522987f893e3902048c55ff

{
"_updated": "Wed, 15 Apr 2015 17:22:07 GMT",
"_created": "Mon, 06 Apr 2015 14:30:23 GMT",
"_id": "5522987f893e3902048c55ff",
"friends": [
    "552e9eb0893e391063045edc"
]
}

PATCH /users/5522987f893e3902048c55ff
{"friends": [“550f288d893e390204b0a5ac”]}

RESPONSE:
{
"_updated": "Wed, 15 Apr 2015 19:38:06 GMT",
"_created": "Mon, 06 Apr 2015 14:30:23 GMT",
"_status": "OK",
"_id": "5522987f893e3902048c55ff"
}

GET /users/5522987f893e3902048c55ff

{
"_updated": "Wed, 15 Apr 2015 19:38:06 GMT",
"_created": "Mon, 06 Apr 2015 14:30:23 GMT",
"_id": "5522987f893e3902048c55ff",
"friends": [
    "550f288d893e390204b0a5ac"
]
}

I have also tried PUT, but it replaces the list with the new value as well.

EDIT: I just tried using POST.

POST /users/5522987f893e3902048c55ff/friends
{"552e9eb0893e391063045edc"}

RESPONSE:
{
"_status": "ERR",
"_error": {
    "message": "The requested URL was not found on the server.  If you entered the URL manually please check your spelling and try again.",
    "code": 404
}
}

AND

POST /users/5522987f893e3902048c55ff
{"friends": ["552e9eb0893e391063045edc"]}

RESPONSE:
{
"_status": "ERR",
"_error": {
    "message": "The method is not allowed for the requested URL.",
    "code": 405
}
}

Source: (StackOverflow)

good use case of HATEOAS

may I have some example/typical use case of HATEOAS? I agree it can be a very powerful concept provide great flexibility but I am not sure how to properly get benefit from HATEOAS. would be great if you can share your experience/use case.


Source: (StackOverflow)