Can I use external methods as route decoders in Python / Flask?

My main application file is a series of method definitions, each of which is bound to a route. I have 3 separate parts for my application (main, admin, api). I'm trying to split methods into external files for better service, but I like Flask's ease of use of route decoders for my application urls.

Currently, one of my routes is as follows:

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

But I would like to extract the get_galleries method to a file containing the methods for my API:

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

The problem is that when I do this, I get an error message. Is this possible, and if so, how to do it?

+6
source share
4 answers

As pointed out in another comment, you can call app.route('/')(api.view_home()) or use Flask app.add_url_rule() http://flask.pocoo.org/docs/api/#flask.Flask .add_url_rule

@app.route() code @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 

You can do the following:

 ## 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) 

And then:

 ## 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) 

I use the method used for destruction. Define all your urls in your own file, and then import urls in __init__.py , which runs app.run()

In your case:

 |-- 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. 
+9
source

Decorators are just functions, so you can just do:

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

The decorator is just a special feature.

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

And in fact, depending on what the decorator can do, you may not need to maintain the result at all.

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

I don’t think you can decorate a method this way. But I suppose that instead of using the decorator as usual, you can create a callback to decorate it manually.

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

Then you can use it as follows:

 import api galleries = wrap_api(api.get_galleries(), '/api/galleries') 
0
source

Source: https://habr.com/ru/post/947387/


All Articles