13

現在、メインのアプリ ファイルは一連のメソッド定義であり、それぞれがルートに関連付けられています。アプリには 3 つの異なる部分 (main、admin、api) があります。メンテナンスを改善するためにメソッドを外部ファイルに分割しようとしていますが、アプリケーションの URL にルート デコレーターを使用するという Flask のシンプルさが気に入っています。

現在、私のルートの1つは次のようになっています。

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

しかし、API のメソッドを含むファイルに get_galleries メソッドを抽出したいと思います。

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

問題は、それを行うとエラーが発生することです。これは可能ですか?

4

4 に答える 4

27

他のコメントで述べたように、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すべてを独自のファイルで定義してから、実行import urlsするファイルで定義します__init__.pyapp.run()

あなたの場合:

|-- app/
|-- __init__.py (where app/application is created and ran)
|-- api/
|   |-- urls.py
|   `-- views.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

from flask import render_template

def call(call):
    # do api call code.
于 2013-06-16T02:24:00.930 に答える
1

デコレータは単なる特別な機能です。

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

実際、デコレータの機能によっては、結果を保持する必要がまったくない場合もあります。

application.route('/api/galleries')(api.get_galleries)
于 2013-06-16T02:21:06.750 に答える
1

デコレータは単なる関数なので、次のようにするだけです:

import api
api.get_galleries = application.route(api.get_galleries, '/api/galleries')
于 2013-06-16T02:27:25.753 に答える
0

そのようにメソッドを装飾することはできないと思います。しかし、デコレータを通常の方法で使用する代わりに、コールバックを作成して手動で装飾することができると思います。

def wrap_api(cls, rt):
  return application.route(rt)(cls)

次に、次のように使用できます。

import api
galleries = wrap_api(api.get_galleries(), '/api/galleries')
于 2013-06-16T02:26:20.983 に答える