sanic的mongodb异步工具,灵感来源自 官方例子 <https://github.com/channelcat/sanic/blob/master/examples/sanic_motor.py).是[motor](https://motor.readthedocs.io/en/stable/tutorial-asyncio.html>
_ 的封装,
目的只是为了简化操作.
motor <https://motor.readthedocs.io/en/stable/tutorial-asyncio.html>
_ 支持的操作都支持sanic>=0.4.1
pip install sanic-mongo
mongo需要给app.config
设置关键字MONGO_URIS
,它是一个由mongodb名字和url组成的字典.
同时也可以使用Mongo.SetConfig(app,**kws)
来注册kws的内容到MONGO_URIS
.
而使用的时候可以访问app.mongo[mongodb名字]
访问对应的db
gridfs与之类似,只是关键字是GRIDFS_SETTINGS
,而访问需要使用app.GridFS[GridFS名字]
.. code:: python from sanic import Sanic from sanic.response import json from sanic_mongo import Mongo
app = Sanic(__name__)
mongo_uri = "mongodb://{host}:{port}/{database}".format(
database='test',
port=27017,
host='localhost'
)
Mongo.SetConfig(app,test=mongo_uri)
Mongo(app)
@app.get('/objects')
async def get(request):
docs = await app.mongo['test'].test_col.find().to_list(length=100)
for doc in docs:
doc['id'] = str(doc['_id'])
del doc['_id']
return json(docs)
@app.post('/objects')
async def new(request):
doc = request.json
print(type(app.mongo['test']))
object_id = await app.mongo['test']["test_col"].save(doc)
return json({'object_id': str(object_id)})
if __name__ == "__main__":
app.run(host='127.0.0.1', port=8000,debug=True)
.. code:: python
from sanic import Sanic
from sanic.response import json,text
from sanic_mongo import GridFS
app = Sanic(__name__)
mongo_uri = "mongodb://{host}:{port}/{database}".format(
database='test',
port=27017,
host='localhost'
)
GridFS.SetConfig(app,test_fs=(mongo_uri,"fs"))
GridFS(app)
@app.get('/pics')
async def get(request):
cursor = app.GridFS["test_fs"].find()
result = [{i._id:i.name} async for i in cursor]
return json({"result":result})
@app.post('/pics')
async def new(request):
doc = request.files.get('file')
async with app.GridFS["test_fs"].open_upload_stream(filename=doc.name,
metadata={"contentType": doc.type}) as gridin:
object_id = gridin._id
await gridin.write(doc.body)
return json({'object_id': str(object_id)})
if __name__ == "__main__":
app.run(host='127.0.0.1', port=8000,debug=True)