我可以在Python/Flask中使用外部方法作为路径修饰器吗?

com*_*ted 12 python flask

我的主应用程序文件目前是一系列方法定义,每个定义都附加到一个路径.我的应用程序(main,admin,api)有3个不同的部分.我正在尝试将方法拆分为外部文件以便更好地维护,但我喜欢Flask在我的应用程序的URL中使用路径装饰器的简单性.

我的其中一条路线目前看起来像这样:

# index.py
@application.route('/api/galleries')
def get_galleries():
    galleries = {
        "galleries": # get gallery objects here
    }
    return json.dumps(galleries)
Run Code Online (Sandbox Code Playgroud)

但我想将get_galleries方法解压缩到包含我的API方法的文件中:

import api
@application.route('/api/galleries')
api.get_galleries():
Run Code Online (Sandbox Code Playgroud)

问题是,当我这样做时,我得到一个错误.这是可能的,如果是这样,我该怎么做?

bnl*_*cas 18

如同其他评论中所述,您可以致电app.route('/')(api.view_home())或使用Flask的app.add_url_rule() http://flask.pocoo.org/docs/api/#flask.Flask.add_url_rule

Flask的@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
Run Code Online (Sandbox Code Playgroud)

您可以执行以下操作:

## 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)
Run Code Online (Sandbox Code Playgroud)

然后:

## 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)
Run Code Online (Sandbox Code Playgroud)

是我用来破坏事物的方法.定义所有你urls自己的文件然后import urls在你__init__.py运行的文件中app.run()

在你的情况下:

|-- app/
|-- __init__.py (where app/application is created and ran)
|-- api/
|   |-- urls.py
|   `-- views.py
Run Code Online (Sandbox Code Playgroud)

API/urls.py

from application import app

import api.views

app.add_url_rule('/call/<call>', 'call', view_func=api.views.call)
Run Code Online (Sandbox Code Playgroud)

API/views.py

from flask import render_template

def call(call):
    # do api call code.
Run Code Online (Sandbox Code Playgroud)