使用mongo db的瓶子应用程序

时间:2016-12-16 20:43:56

标签: python mongodb rest pymongo bottle

我正在使用Bottle和Mongo数据库尝试一般的REST API。

我在地址127.0.0.1:8010/上的网页上收到的错误是

  

错误:404未找到

     

抱歉,请求的URL http://127.0.0.1:8010 /导致错误:

     

未找到:' /'

在命令行中,我得到了这个:

$ python myrestapi.py

Bottle v0.12.10 server starting up (using WSGIRefServer())...
Listening on "http://127.0.0.1:8010/"
Hit Ctrl-C to quit.
127.0.0.1 - - [17/Dec/2016 01:54:46] GET / HTTP/1.1 404 720

这是我的文件代码/ myrestapi.py:

import json
import bottle

from bottle import route, run, request, abort
from pymongo import Connection

connection = Connection('localhost', 27017)
db = connection.mydatabase
app = bottle.Bottle()

@app.route('/documents', method='PUT')
def put_document():
  data = request.body.readline()

  if not data:
   abort(400, 'No data received')
   entity = json.loads(data)

  if not entity.has_key('_id'):
   abort(400, 'No _id specified')

try:
  db['documents'].save(entity)

  except ValidationError as ve:

  abort(400, str(ve))

@app.route('/documents/:id', method='GET')
def get_document(id):
entity = db['documents'].find_one({'_id':id})
if not entity:
    abort(404, 'No document with id %s' % id)
return entity

bottle.run(host='localhost', port=8010)

1 个答案:

答案 0 :(得分:1)

  

错误:404未找到

当我们寻找的restful api不可用时,会抛出404错误。

在这种情况下,如果您尝试过/documents/documents/1,那么您会收到回复,因为您有@app.route('/documents', method='PUT')@app.route('/documents/:id', method='GET')

有关详细信息,请参阅

http://www.restapitutorial.com/lessons/httpmethods.html

REST API 404: Bad URI, or Missing Resource?