使用Flask-Restful从应用程序上下文获取数据库连接 [英] Getting the database connection from application context with Flask-Restful

查看:370
本文介绍了使用Flask-Restful从应用程序上下文获取数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用Flask-Restful的应用程序,我不知道如何从应用程序上下文获取数据库连接信息。



这是我所拥有的远:



app.py:

  .... 
from flask.ext.restful import reqparse,abort,Api,Resource
app = Flask(__ name__)
app.config ['DATABASE'] ='我的。 db'
api = Api(app)
api.add_resource(Foo,'/')

foo.py

  ... 
from flask.ext .restful import Resource
$ b class Foo(Resource):
def __init __(self):
self.db = get_db()
def post(self):
do_stuff_with_db()

我想要get_db方法如下所示:

  def get_db():
return database.connect(app.config ['DATABASE'])

问题是为了将app.config放到foo中。 py,我创建了一个循环引用。有没有一个干净,希望idomatic方式来获得这个?



我已经看到,但是给出的解决方案实际上并不能解决循环导入的问题。

那么,对于我的项目,我使用这种结构:
$ b

application / __ init__。 py



  ... 
app = Flask(__ name__)
...
db = SQLAlchemy(app)#因为我使用sqlalchemy
...
导入application.core



application / core.py



  from application.api import resource 
...
#api definition



application / api / resource.py



  from application import db 
...
db.doWhatEverYouWant()
...

这当然不是完美的,但我不知道没有这样的循环进口问题。

I have an app using Flask-Restful and I don't know how to get the database connection info from the application context.

Here is what I have so far:

app.py:

....
from flask.ext.restful import reqparse, abort, Api, Resource
app = Flask(__name__)
app.config['DATABASE'] = 'my.db'
api = Api(app) 
api.add_resource(Foo, '/')

foo.py

...
from flask.ext.restful import Resource

class Foo(Resource):
    def __init__(self):
        self.db = get_db()
    def post(self):
        do_stuff_with_db()

I'd like the get_db method to look something like:

def get_db():
    return database.connect(app.config['DATABASE'])

The problem is in order to get app.config into foo.py, I create a circular reference. Is there a clean, and hopefully idomatic way to get this?

I have seen this question, but the solution given doesn't actually resolve the circular import problem.

解决方案

Well, for my project I use this kind of structure:

application/__init__.py

...
app = Flask(__name__)
...
db  = SQLAlchemy(app) #because I use sqlalchemy
...
import application.core 

application/core.py

from application.api import resource
...
# api definition

application/api/resource.py

from application import db
...
db.doWhatEverYouWant()
...

It's certainly not perfect but I don't have such kind of circular import problems.

这篇关于使用Flask-Restful从应用程序上下文获取数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆