Getting "Unresolved reference 'app'" despite importing Flask - python

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.

Related

Python Flask "The configuration file does not exist." accessing sub-path

I am deploying Flask on CPanel, and basic configurations are working correctly,
up to the point that I can access home route, defined as:
#app.route("/home")
#app.route("/")
def home():
return "This is home page, blah blah blah"
The site can be thought of, as being accessed at
https://sub-domain.main-domain.com/base-url,
thus, home page is accessed as https://sub-domain.main-domain.com/base-url/ and that works perfectly.
Problem
So, the issue comes when I access any other route, other than the slash("/"),
in the above example, for instance, accessing
https://sub-domain.main-domain.com/base-url/home,
doesn't seem to work at all, and results in
The configuration file does not exist. error.
Any possible help would be kindly appreciated. my passenger_wsgi.py is configured as:
import sys
# add your project directory to the sys.path
base_dir = u'/home/cpaneusername/base-dir'
if base_dir not in sys.path:
sys.path = [base_dir] + sys.path
# import flask app but need to call it "application" for WSGI to work
from app import website as application
Nevertheless, thanks for the assistance.
What I can suggest resolving the issue is to change the base URL of your Python app and remove any sub-folders from it. For example, just keep it that way:
https://sub-domain.main-domain.com/
And try again.
Otherwise, you might want to change the /home route of your app to this one instead:
#app.route("/base-url/home")
If none of the above works, then make sure that you have the correct .htaccess rules in place to forward the requests properly to your app, but I assume you already have considering the fact that you are able to access the / of the app.
I tried moving the Python app and other supporting modules to /public folder, and in the wsgi file, I imported as
from public.app import website as application
There, it worked.

Is it possible to change code of flask without rerunning the flask server after deployment?

Consider, I have a flask server deployed which routes to multiple webpages. If I want to change content of one route, by changing its code, is it possible to reflect those changes in webpages without rerunning the flask server? It is possible to host and rerun other scripts on the linux server or entriely another flask server as long as the website url(port number and route) doesn't change.
Please suggest any way you can come up with!
setting flask environment will do the thing for you in the shell.
export FLASK_ENV=development
Assuming you are using flask development server,
Yes, its possible using use_reloader=True,
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
# You business logic code
return some_data
if __name__ == '__main__':
app.run(debug=False, host='0.0.0.0', port=8000,
use_reloader=True, threaded=True)
However it is not good idea to use it in production, related Is the server bundled with Flask safe to use in production?
My assumption is that you want your deployment service to recognize that a change has occurred in a file, which prompts it to automatically restart to reflect the changes, rather than you manually restarting the service.
Assuming that you are deploying on a production uWSGI server, starting the service with touch-reload=/path/to/folder would allow uWSGI to reload when the specified file/folder is modified or touched. https://uwsgi-docs.readthedocs.io/en/latest/Options.html#touch-reload
--touch-reload=/path/to/file.txt
I think you can only do this with the Apache Webserver. Refer to the Flask documentation.
I haven't tried it (yet), but when you have deployed your new code any small change in the wsgi-file should automatically reload the code.
You mentioned two requirements
I have a flask server deployed
I would assume you mean it is deployed in a production environment. This automatically rules out debug-mode from the development server, because it is not stable, efficient or secure for production use.
Without rerunning the flask server
This rules out autoreload, because this will completely restart your server. Any requests that come in until the server is ready again will fail.
One way of going about is by running your application with debug mode ON through app.run(debug=True)
The problem with this approach is that your application would be exposed over the internet with the application's internal debugger on which shouldn't be done.
A better way I can think of is to call the functions you need to change frequently from a different file other than where your core flask code exists and change in that file whenever needed. This way you don't need to change your Flask code and you won't need to restart the application
Edit:
A sample Flask route would be
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
# Route's business logic usually goes here
return data
Now, instead of writing your application's business logic in the same file as your route, you could simply write it in a different file as follows and import it in the file with the route:
File with the business logic
def process_hello_world(params):
# Write your business logic here which you want to change without reloading the application
return data
And in the application file with the route call the business logic as follows:
from flask import Flask
from
app = Flask(__name__)
#app.route('/')
def hello_world():
data = process_hello_world()
return data

How to register blueprint level error handler in Flask 1.0.2?

This article for flask 1.0.x mentions we must use app_errorhandler (example:#bp.app_errorhandler)
This and this SO answers also mention that we must use app_errorhandler (example:#bp.app_errorhandler)
This article for flask 1.0.x mentions we must use errorhandler (example: #bp.errorhandler)
Why does documentation for 1.0.x mention 2 different things and which is the correct approach to register blueprint level error handler in Flask 1.0.2?
There are no correct or incorrect approach for this kind of situation,
I definitely recommend you to use the Blueprint level error handler #bp.errorhandler, but for specific errors that are directly related to Models/Helpers/Services/...etc inside of your Blueprint execution.
However, I recommend you to handle errors that are common on all blueprints and their responses are pretty much the same on each blueprint, with your Flask app error handler #app.errorhandler.
This way you will remove any duplicate logic for error handling.

FLASK: Does the code outside the routers get executed every time a new request comes in?

The following is a basic flask app:
from flask import Flask, render_template, request
import pickle
import os
cur_dir = os.path.dirname(__file__)
clf = pickle.load(open(os.path.join(cur_dir, 'pkl_objects/classifier.pkl'), 'rb'))
#app.route('/')
def index():
return "RESPONSE"
Now my question is whether the model is loaded every time a new request is made to this server or is it loaded just once and only the routes get executed for every incoming request? This is hard to figure out using a simple Flask development server since it contains only one thread. So if a deployment server spawns a thread for each request, will the loading of model happen each time?
Your code is a regular python code. What happens when you start the application is that your Python WSGI HTTP Server (there are plenty of WSGI servers like gunicorn) loads this script and verifies the minimal requirements for a WSGI Servers (which flask takes care of). See here for details. This server might start several instances of this script for performance purposes, then your model will be loaded several times.
Then what happens when a request is made is that the server balances this request in one of the previously started process and access the flask object in it directly (so it doesn't reload the code). However, some servers might adapt the number of process depending on the number of request, and your model will be reloaded.

Server Error in Default Deployment of Azure Flask Web App

I'm trying to deploy a Flask app within Azure, using the pre made template created by Azure.
I can't get a simple...
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello():
return "Hello World!"
if __name__ == '__main__':
app.run()
To do anything. To simplify further still, even the pre made deployment returns an error...
Clearly I'm misunderstanding something very fundamental here.
Using FTP I can see the files that Azure is creating - sure does look like there should be a nice little demo site.
What am I doing wrong?
Cheers, Ben
According to your description, I think the issue was caused by some incorrect configuration in the web.config & the Application Settings of your WebApp settings. Please try to refer to the blog to resolve it.
Meanwhile, I don't know what pre made template created by Azure you used. I tried to create a new Azure WebApp for Flask as below.
The file list in the wwwroot path in the Kudu tool or FTP shown as below.
Then, I modified the code views.py in the FlaskWebProject1 directory. And it works.
It seems to be more simple. Hope it helps.
I've been figthing the same issue for a while, I have only be able to workaround it by changing the pricing tier associated to the "service plan" to S2 Standard. If I try to use S1 Standard I run into the same issues.

Categories

Resources