I have been using flask for a while. I made an app implementing the application factory design pattern, but I can't understand the use of boo in the below-mentioned code.
from flask import Blueprint
some_blueprint = Blueprint("boo", __name__)
The first parameter of the Blueprint constructor (in your case boo) is simply a symbolic name that you assign to the Blueprint object.
Check out this link: https://flask.palletsprojects.com/en/2.0.x/tutorial/views/
Related
I'm learning web developing for simple applications and I've created one that uses before_first_request decorator. According with the new release notes, the before_first_request is deprecated and will be removed from Flask 2.3:
Deprecated since version 2.2: Will be removed in Flask 2.3. Run setup
code when creating the application instead.
I don't understand how I can update my code to be complacent with flask 2.3 and still run a function at first request without using before_first_request. Could some kind soul give me an example ?
I don't know if this is answered but for anyone looking for the answer:
in place of the #app.before_first_request decorated function use the app instance like this:
i.e.
# In place of something like this
#app.before_first_request
def create_tables():
db.create_all()
...
# USE THIS INSTEAD
with app.app_context():
db.create_all()
This question already has answers here:
Split Python Flask app into multiple files
(4 answers)
Closed 2 years ago.
I'm building a small flask application and I want to have a modular structure in my project.
In Django I could just write two separate folders with their own urls.py, register them in my settings.py and create routes to them in base urls.py.
How to achieve this kind of modularity in flask?
Preferably with as little code as possible.
Bonus points if all this can be easily done without extensions.
You are looking for blueprints.
app.py
blueprints/
sample_blueprint.py
another_blueprint.py
Blueprints are like apps but not apps. (very lame explanation but let me show you some code)
# sample_blueprint.py
from flask import Blueprint
# just like `app = Flask(__name__)`
SAMPLE_BLUEPRINT = Blueprint('sample_blueprint', __name__)
# just like `#app.route('/sample')`
#SAMPLE_BLUEPRINT.route('/sample')
def sample():
return 'Sample'
And then in app.py you have to register it.
# app.py
from flask import Flask
from blueprints.sample import SAMPLE_BLUEPRINT
app = Flask(__name__)
# Register all the blueprints, url_prefix is optional
app.register_blueprint(SAMPLE_BLUEPRINT, url_prefix='/sample-br')
if __name__ == '__main__':
app.run(debug=True)
You can now run the app (python3 app.py) and goto localhost:5000/sample-br/sample and see the response of the blueprint route.
This code is not tested. It is just to give you a starting idea. Please read the docs and try it out on your own and find out how blueprints fit into a Flask project.
I'm trying to implement the get_my_ip() method from flask. I'm getting an unresolved reference despite importing the relevant packages. I found solutions for similar issues that say that I have folder named 'app', which causes the problem, but I couldn't find such folder.
The code:
from flask import request
from flask import jsonify
#app.route("/get_my_ip", methods=["GET"])
def get_my_ip():
return jsonify({'ip': request.remote_addr}), 200
The function is called as follows:
with open('file.txt, 'a') as f:
f.write(f'ip: {get_my_ip()}')
Thanks.
To answer the question title
You haven't actually defined app. You can't use the decorator to add routes to an application that you haven't even defined.
from flask import Flask, request, jsonify
app = Flask(__name__) # See here
#app.route("/get_my_ip", methods=["GET"])
def get_my_ip():
return jsonify({'ip': request.remote_addr}), 200
I strongly suggest The Flask Megatutorial because this is a fundamental misunderstanding.
To answer what you're trying to do - this is horribly misguided. You're trying to snag on to some functionality from Flask without actually running an application. Flask is not a server. You could have any number of levels of actual servers before things got to the level of your code. For example, Apache or Nginx, then gunicorn. All of those could capture the IP.
I am trying to have one service which will fulfill two related functions. I would like to have something like this for my REST api:
/route1/get/as_text
/route2/get/as_json
In nodejs, you can pass off a collection of routes from some base URL by saying:
app.use('/route1/', route1.js)
app.use('/route2/', route2.js)
and then the route1.js will have routes defined like this:
app.router('/as_text', function(){//some stuff})
When I do this, can define a set of routes, that all have /route1/ as the basis of the URL. I would like to do something similar in flask, where I just define the first section of the url, and add all logic of that section of the API into a file which is separate to another section of the api.
Is this possible in flask? Or should I look for a new approach?
You'll want to take a look at Blueprints.
When defining your application, you can register Blueprints with a path prefix:
app = Flask(__name__, template_folder='views')
app.register_blueprint(controllers.route1, url_prefix="/route1")
app.register_blueprint(controllers.route2, url_prefix="/route2")
Then define the controllers for these routes in separate files.
route1 = Blueprint('route1', __name__, template_folder='views')
#route1.route('/get/as_text',methods=['GET'])
def get_as_text_route():
return json.jsonify(data="my data")
You could also checkout Flask Restful for creating REST APIs in with Flask.
I liked a lot of the conventions the Overholt example used, but ran into a specific problem.
I have two apps set up using the DispatcherMiddleware object from werkzeug.wsgi:
from werkzeug.wsgi import DispatcherMiddleware
from myapp import api, frontend
application = DispatcherMiddleware(frontend.create_app(), {
'/api': api.create_app()
})
This works great; the end points are all there. Inspecting application.app.url_map shows the mappings for frontend, and application.mounts['/api'].url_map shows the mappings for api correctly.
The problem I'm running into is I'd like to use url_for() in my frontend templates for methods in api, but haven't found a way to make that work. Hardcoding the URL paths works, but will cause problems later if I want to move things around.
What you can do is add a new route to your back-end, say /api/route-map which spits out a map (dictionary/JSON) of the routes (you can use url_for to generate the map) and hit this route from your front-end to get the dynamic route map, which you can use through out your front-end templates with your custom jinja2 function (which you can create as shown below).
def api_url_for(route_fn_string):
"""
This is just boilerplate code. Please do some checking here.
'"""
return route_map[route_fn_string]
app.jinja_env.globals.update(api_url_for=api_url_for)
Now you can do {{api_url_for('update')}} in your jinja2 template to get its actual route.
If you're putting both the apps on the same server, then you can simply share the route map as a global or through a getter function.