我可以在Python/Flask中使用外部方法作为路由装饰器吗? [英] Can I use external methods as route decorators in Python/Flask?
问题描述
我的主应用程序文件当前是一系列方法定义,每个方法定义都附加到一条路线上.我的应用程序有3个不同的部分(主要,管理,API).我正在尝试将方法拆分为外部文件以进行更好的维护,但是我喜欢Flask在为应用程序的URL使用路由装饰器时的简单性.
My main app file is currently a series of method definitions, each attached to a route. I've got 3 distinct parts to my app (main, admin, api). I'm trying to split out methods into external files for better maintenance but I like Flask's simplicity in using route decorators for my application's URLs.
我的一条路线目前看起来像这样:
One of my routes currently looks like this:
# index.py
@application.route('/api/galleries')
def get_galleries():
galleries = {
"galleries": # get gallery objects here
}
return json.dumps(galleries)
但是我想将get_galleries方法提取到一个包含我的API方法的文件中:
But I'd like to extract the get_galleries method into a file containing methods for my API:
import api
@application.route('/api/galleries')
api.get_galleries():
问题是,当我这样做时,我得到一个错误.这可能吗?如果可以,我该怎么办?
The problem is that when I do that I get an error. Is this possible, and if so how do I do it?
推荐答案
就像其他注释中所述,您可以致电app.route('/')(api.view_home())
或使用Flask的app.add_url_rule()
http://flask.pocoo.org/docs/api/#flask.Flask.add_url_rule
Like stated in the other comment, you can call app.route('/')(api.view_home())
or use Flask's app.add_url_rule()
http://flask.pocoo.org/docs/api/#flask.Flask.add_url_rule
烧瓶的@app.route()
代码:
def route(self, rule, **options):
def decorator(f):
endpoint = options.pop('endpoint', None)
self.add_url_rule(rule, endpoint, f, **options)
return f
return decorator
您可以执行以下操作:
## urls.py
from application import app, views
app.add_url_rule('/', 'home', view_func=views.home)
app.add_url_rule('/user/<username>', 'user', view_func=views.user)
然后:
## views.py
from flask import request, render_template, flash, url_for, redirect
def home():
render_template('home.html')
def user(username):
return render_template('user.html', username=username)
是我用来分解事物的方法.在自己的文件中定义所有urls
,然后在运行app.run()
Is the method I use for breaking things down. Define all your urls
in it's own file and then import urls
in your __init__.py
that runs app.run()
在您的情况下:
|-- app/
|-- __init__.py (where app/application is created and ran)
|-- api/
| |-- urls.py
| `-- views.py
api/urls.py
api/urls.py
from application import app
import api.views
app.add_url_rule('/call/<call>', 'call', view_func=api.views.call)
api/views.py
api/views.py
from flask import render_template
def call(call):
# do api call code.
这篇关于我可以在Python/Flask中使用外部方法作为路由装饰器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!