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

2024-06-13 06:05:55 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我的一条路线目前看起来是这样的:

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

但我想将get_galleries方法提取到一个包含我的API方法的文件中:

import api
@application.route('/api/galleries')
api.get_galleries():

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


Tags: 文件方法api应用程序urlflask路由get
3条回答

装饰只是一种特殊的功能。

routed_galleries = application.route('/api/galleries')(api.get_galleries)

实际上,取决于装饰者做了什么,您可能根本不需要保留结果。

application.route('/api/galleries')(api.get_galleries)

Decorators只是函数,所以您可以执行以下操作:

import api
api.get_galleries = application.route(api.get_galleries, '/api/galleries')

如其他注释中所述,您可以调用app.route('/')(api.view_home())或使用Flask的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()__init__.py中定义import urls

就你而言:

|-- app/
|-- __init__.py (where app/application is created and ran)
|-- api/
|   |-- urls.py
|   `-- views.py

api/url.py

from application import app

import api.views

app.add_url_rule('/call/<call>', 'call', view_func=api.views.call)

api/视图.py

from flask import render_template

def call(call):
    # do api call code.

相关问题 更多 >