Code Monkey home page Code Monkey logo

sanic-motor's Introduction

sanic-motor

Simple motor wrapper for Sanic.

Notice:
version 0.5 requires Sanic >= 21.3

Works on Sanic >= 0.4.0 and MOTOR_URI need to be defined in app.config

Installation

pip install sanic-motor

Usage

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from sanic import Sanic
from sanic.response import json
from sanic_jinja2 import SanicJinja2

from sanic_motor import BaseModel

app = Sanic(__name__)

settings = dict(
    MOTOR_URI='mongodb://localhost:27017/myapp', LOGO=None
)
app.config.update(settings)

BaseModel.init_app(app)
jinja = SanicJinja2(app, autoescape=True)


class User(BaseModel):
    __coll__ = 'users'
    __unique_fields__ = ['name']
    # __unique_fields__ = ['name, age']   # name and age for unique


@app.route('/')
async def index(request):
    cur = await User.find(sort='name')
    return jinja.render('index.html', request, users=cur.objects)


@app.route("/show/<id>")
async def show(request, id):
    # add as_raw = True to get the dict format record
    user_dict = await User.find_one(id, as_raw=True)

    # user = await User.find_one(id)
    return json(dict(user=user_dict))


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8000, debug=True)

see examples and source code for details.

Run example:

$cd example
$virtualenv venv
$. venv/bin/activate
$pip install -r requirements.txt
$python myapp.py

Open http://localhost:8000 to see the example page.

example

sanic-motor's People

Contributors

lixxu avatar quillfires avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

sanic-motor's Issues

Please Update README.md

Hi there, I use sanic-motor today, I think this is a great project, but your document is too simple and outdated, which makes me confused.

some functions such as find() and find_one() are different than your example usage, I found these can't find any document by your example way. I need add as_raw and some other params can get the result, like this:

document = await Test.find_one({"id": "tw1296781020646313999"}, {"_id": 0}, as_raw=True)
document = await Test.find(request, {"id": "tw1296781020646313999"}, {"_id": 0}, as_raw=True)

This is really a waste of time, can you update your README.md or update your examples in your free time ?
Looking forward to your reply, thank you very much!

Import error: 'GEOHAYSTACK'

Hey,

i wanted to try the framework with pymongo however I got this issue:

  File "D:\Coding\Trader_server\app.py", line 7, in <module>
    from sanic_motor import BaseModel
  File "D:\Coding\Trader_server\traderEnv\lib\site-packages\sanic_motor\__init__.py", line 7, in <module>
    from pymongo import (
ImportError: cannot import name 'GEOHAYSTACK' from 'pymongo' (D:\Coding\Trader_server\traderEnv\lib\site-packages\pymongo\__init__.py)

Code has been copied from the repo example.

Current installed package versions are:

------------- -------
aiofiles      22.1.0
dnspython     2.2.1
httptools     0.5.0
motor         3.1.1
multidict     6.0.3
pip           22.3.1
pymongo       4.3.3
sanic         22.9.1
sanic-motor   0.6.0
sanic-routing 22.8.0
setuptools    65.5.1
websockets    10.4
wheel         0.38.4

any help please?

thank you for your time and answer

Connect 2 database???

Hi, sanic-motor is very easy to use, with specify MOTOR_URI and using BaseModel. But what if i want to connect to 2 database in the same sanic application??? Any examples about it??

find() is not returning results

@bp_v1.route("/companies", methods=["GET"])
async def handle(request):
query = {}
cur = await Company.find(filter=query)
results = cur.objects
return json({"Status": "Success", "companies": results})

The above query is giving error that coroutine is not callable or NoneType is not callable. I tried all variations of filter or even to_list but not working. The below query worked fine though.

@bp_v1.route("/companies/add", methods=["POST"])
async def handle(request):
if request.method == 'POST':
company = request.json
res = await Company.insert_one(company)
if res:
return json({"Status": "Success"})
else:
return json({"Status": "Error"})

Travis fails when trying to install 0.3.3

I have sanic_motor dependency on the development requirements for sanic_session and with the latest version it fails to build because of error setup.py. The full log is available by the link:
https://travis-ci.org/xen/sanic_session/jobs/421046411.

Traceback:

https://files.pythonhosted.org/packages/3f/12/de495223524a2eaca52fdb6b13e8f5bacbd9bbac67711aa8e1c9a4007559/sanic-motor-0.3.3.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-95qurk4c/sanic-motor/setup.py", line 15, in <module>
        with p.open(encoding='utf-8') as f:
      File "/opt/python/3.5.6/lib/python3.5/pathlib.py", line 1151, in open
        opener=self._opener)
      File "/opt/python/3.5.6/lib/python3.5/pathlib.py", line 1005, in _opener
        return self._accessor.open(self, flags, mode)
      File "/opt/python/3.5.6/lib/python3.5/pathlib.py", line 371, in wrapped
        return strfunc(str(pathobj), *args)
    NotADirectoryError: [Errno 20] Not a directory: '/tmp/pip-install-95qurk4c/sanic-motor/setup.py/../sanic_motor/__init__.py'
    
    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-95qurk4c/sanic-motor/

UserWarning

sanic/base.py:35: UserWarning: Setting variables on Sanic instances is deprecated and will be removed in version 21.9. You should change your Sanic instance to use instance.ctx.motor_clients instead.

Mongodb geospetial query doesnt work

Hi,
i am trying to use mongodb geospetial query with sanic-motor.

Find with no arguments runs well and my query works in MongoDB Compass.
My query : await DataPoint.find({"location.cordinates": { '$nearSphere' : {'$geometry': { type: "Point", 'coordinates': [20.44974230, 44.8772 ] },'$minDistance': 0,'$maxDistance': 80}}})

Can you help me? I can't solve it.
slika1

Thanks in advance,
Petar

Error in find() when use $gte and $lt

Hi, I want to use $gte and $lt as my query condition. But there are some error occur.

Here is my code:

query = {'Date': {'$gte': today,'$lt': today + timedelta(days=1)}}
cur = await Battle.find(query)

And the error:

File "main.py", line 46, in home
    cur = await Battle.find(query)
  File "/home/jacob/Python/Part_Time/website/VENV/lib/python3.5/site-packages/sanic_motor/__init__.py", line 165, in find
    per_page_name)
  File "/home/jacob/Python/Part_Time/website/VENV/lib/python3.5/site-packages/sanic_motor/__init__.py", line 144, in get_page_args
    page = request.args.get(page_name, 1)
AttributeError: 'dict' object has no attribute 'args'

When I use this query condition in pymongo, it just work fine.
Would you help me to find the problem?
Thanks

TypeError: MotorDatabase object is not callable with motor==2.0.0

Full traceback

[2018-08-15 21:45:40 +0300] [26229] [ERROR] Experienced exception while trying to serve
Traceback (most recent call last):
  File "/home/envs/pgate/lib/python3.6/site-packages/sanic/app.py", line 646, in run
    serve(**server_settings)
  File "/home/envs/pgate/lib/python3.6/site-packages/sanic/server.py", line 588, in serve
    trigger_events(before_start, loop)
  File "/home/envs/pgate/lib/python3.6/site-packages/sanic/server.py", line 496, in trigger_events
    loop.run_until_complete(result)
  File "uvloop/loop.pyx", line 1422, in uvloop.loop.Loop.run_until_complete
  File "/home/envs/pgate/lib/python3.6/site-packages/sanic_motor/__init__.py", line 89, in open_connection
    BaseModel.default_open_connection(app, loop, name, uri)
  File "/home/envs/pgate/lib/python3.6/site-packages/sanic_motor/__init__.py", line 103, in default_open_connection
    db = client.get_default_database()
  File "/home/envs/pgate/lib/python3.6/site-packages/motor/core.py", line 460, in __call__
    database_name, client_class_name))
TypeError: MotorDatabase object is not callable. If you meant to call the 'get_default_database' method on a AsyncIOMotorClient object it is failing because no such method exists.
Traceback (most recent call last):
  File "/snap/pycharm-professional/80/helpers/pydev/pydevd.py", line 1664, in <module>
    main()
  File "/snap/pycharm-professional/80/helpers/pydev/pydevd.py", line 1658, in main
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/snap/pycharm-professional/80/helpers/pydev/pydevd.py", line 1068, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/snap/pycharm-professional/80/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/home/pubgate/run_api.py", line 7, in <module>
    app.run(host="0.0.0.0", port=8000)
  File "/home/envs/pgate/lib/python3.6/site-packages/sanic/app.py", line 646, in run
    serve(**server_settings)
  File "/home/envs/pgate/lib/python3.6/site-packages/sanic/server.py", line 588, in serve
    trigger_events(before_start, loop)
  File "/home/envs/pgate/lib/python3.6/site-packages/sanic/server.py", line 496, in trigger_events
    loop.run_until_complete(result)
  File "uvloop/loop.pyx", line 1422, in uvloop.loop.Loop.run_until_complete
  File "/home/envs/pgate/lib/python3.6/site-packages/sanic_motor/__init__.py", line 89, in open_connection
    BaseModel.default_open_connection(app, loop, name, uri)
  File "/home/envs/pgate/lib/python3.6/site-packages/sanic_motor/__init__.py", line 103, in default_open_connection
    db = client.get_default_database()
  File "/home/envs/pgate/lib/python3.6/site-packages/motor/core.py", line 460, in __call__
    database_name, client_class_name))
TypeError: MotorDatabase object is not callable. If you meant to call the 'get_default_database' method on a AsyncIOMotorClient object it is failing because no such method exists.
sys:1: RuntimeWarning: coroutine 'register_admin' was never awaited
sys:1: RuntimeWarning: coroutine 'Loop.create_server' was never awaited

If switch back to motor==1.2.2 and pymongo==3.6.1 , works correctly

关于find

大神,何时有时间可以提供下find详细点API说明,复杂点查询都搞晕了

Python3.7 pip install fails - latest version (0.3.2)

`Collecting sanic-motor
Using cached https://files.pythonhosted.org/packages/ab/02/fc722087268ee5a62778b3c381a8cb0bf4f3f655452629810a57a7f2a47e/sanic-motor-0.3.2.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "/private/var/folders/t8/cx90qfnj1bz73tr_1fsj6rzw0000gn/T/pip-install-7n_ronkj/sanic-motor/sanic_motor/init.py", line 5, in
from sanic.log import logger
ModuleNotFoundError: No module named 'sanic'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/private/var/folders/t8/cx90qfnj1bz73tr_1fsj6rzw0000gn/T/pip-install-7n_ronkj/sanic-motor/setup.py", line 9, in <module>
    import sanic_motor
  File "/private/var/folders/t8/cx90qfnj1bz73tr_1fsj6rzw0000gn/T/pip-install-7n_ronkj/sanic-motor/sanic_motor/__init__.py", line 7, in <module>
    from sanic.log import log as logger
ModuleNotFoundError: No module named 'sanic'

`

Error when running more than one test case

I found a strange issue when we are running more than one test case. I am getting back an error in the second test case "Future attached to a different loop". You can replicate this by running 2 test cases for your example app like below

def test_index():
    request, response = app.test_client.get('/')
    assert response.status == 200


def test_index_again():
    request, response = app.test_client.get('/')
    assert response.status == 200

I was able to narrow down the issue and it is with the BaseModel.get_collection function and more specifically the reusing of cls.__collection__ in the below statements

if not cls.__collection__:
    cls.__collection__ = cls.__motor_db__[cls.__coll__]

Removing the if condition has solved the issue. Not sure what other consequence this would have...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.