how to use a variable to define a directory flask python3 - python

I have this sample code below, when I try to go to / I get a 404 error, I am trying to use variables as app routes but with no luck
from flask import Flask
app = Flask(__name__)
index_dir = "/"
app.route(index_dir)
def index():
return "hello_world"
if __name__ == '__main__':
app.run(host="0.0.0.0")
Any idea on how to make python3 variables to directories

You have skipped the decorator symbol (#) before app.route(index_dir). It should be like this to work:
from flask import Flask
app = Flask(__name__)
index_dir = "/"
#app.route(index_dir)
def index():
return "hello_world"
if __name__ == '__main__':
app.run(host="0.0.0.0")

Related

Flask application in spyder

I am trying to run a simple flask application in spyder(anaconda). But I am not getting expected results. Can anyone help me here?
from flask import Flask
app = Flask(__name__)
def return_val(a):
return a+1
#app.route('/')
def index():
return return_val(8)
if __name__ == "__main__":
app.run(port=8080)
I am expecting 9 to be printed on the application.

Python - access flask app context before serving requests

Usecase: I have a python flask app that runs background_function() before serving any requests on routes.
When I execute the flask app, I receive the error - RuntimeError: Working outside of application context. I receive the error since I try to get the application context before any request is served.
What is the best pythonic way to execute the background_function() in this example?
from flask import Flask
from download import Download
app = Flask(__name__)
app.config.from_pyfile('config.py')
# run backgroung function
Download.background_function()
#app.route('/')
def index():
return 'Welcome!'
if __name__ == '__main__':
app.run()
The config file
FILE_LOCATION = os.environ['FILE_LOCATION'] # "file/path/on/server"
# Many other variables are present in this file
The download file
from flask import current_app as app
class Download:
#staticmethod
def background_function():
file_path = app.config["FILE_LOCATION"]
# code to download file from server to local
return
Try this:
from flask import Flask
from download import Download
app = Flask(__name__)
#app.route('/')
def index():
return 'Welcome!'
if __name__ == '__main__':
Download.background_function()
app.run()
the download file
from flask import current_app as app
class Download:
#staticmethod
def background_function():
print("testing")
given output:
testing
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
As you can see, the function runs first and prints testing and then runs the application.

It does not recognize the route /greeting

I'm new to flask, I'm trying to do a rest api, but when creating my route it doesn't recognize it for me.
I have imported flask and python 3.8.
from products import products
from flask import Flask
#app.route('/greeting')
def greeting():
return 'hi'
if __name__ == '__main__':
app.run(debug=True, port=4000)
You need to create the instance of the Flask class
app = Flask(__name__)
A minimal Flask application looks something like this:
from flask import Flask
app = Flask(__name__)
#app.route('/greeting')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True, port=4000)
Now you could see it running at:
* Running on http://127.0.0.1:4000/
Access the greeting as http://127.0.0.1:4000/greeting
For more info read this

python code doesn't work when I segregate into packages | works fine in same file

I am trying to build some restful API's. When I try to segregate code into packages the service doesn't work and I get URL not found on the server. For examples:
Scenario 1 [Works fine as I have everything in main.py]
from flask import Flask, jsonify, request
app = Flask(__name__)
#app.route('/echo', methods=['POST'])
def echo():
message = request.get_json().get('message', '')
return jsonify({'message': message})
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080, debug=True)
Now when I try to segregate the code into different packages, it just doesn't work. For example:
Scenario 2 [Doesn't work as the code is in different packages]
I am initializing the app in api/restful.py
from flask import Flask, jsonify, request
app = Flask(__name__)
Then created a service in api/endpoints/service.py
from api.restplus import app, jsonify, request
#app.route('/echo', methods=['POST'])
def echo():
message = request.get_json().get('message', '')
return jsonify({'message': message})
Finally in main.py
from api.restplus import app
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080, debug=True)
It seems like the service is not visible to the app when I put it in a different package. Please advise.
Assuming that the issue you get is that flask does not see your service it looks like nothing is importing your service code once you split your code.
Simply modify your main.py file to look like this to fix it:
from api.restplus import app
import api.endpoints.service
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080, debug=True)
Hope this helps !
You may want to do this way Or I would suggest, if there are less routes try to have everthing in one file.
from yourfile import app
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080, debug=True)
In yourfile.py
from flask import Flask, jsonify, request
app = Flask(__name__)
#app.route('/echo', methods=['POST'])
def echo():
message = request.get_json().get('message', '')
return jsonify({'message': message})

Built a new Flask app -- old one still showing in browser

I made the following file yesterday.
# import flask
from flask import Flask
from flask import render_template
from flask import request
app = Flask(__name__)
# create url & function mapping for root or /
#app.route('/')
def index():
return "Hello from Flask"
# create another mapping name /hello
#app.route('/hello')
def hello():
myName = "kayak"
return "Hello again !!" + myName
# create mapping for /myprofile
#app.route('/myprofile')
def showmyprofile():
return render_template('myprofile.html')
# create mapping for /myprofile
#app.route('/addprofileform')
def addprofileform():
return render_template('myprofileform.html')
# create a mapping for /addprofile
#app.route('/addprofile')
def addprofile():
myname = request.args.get('myname')
state_of_residence = request.args.get('state_of_residence')
return render_template('myprofile.html', html_page_name=myname,
html_page_state_of_residence=state_of_residence)
if __name__== '__main__':
app.run()
Then I made the following file today.
from flask import Flask
app = Flask(__name__)
#app.route('/')
def index():
return 'This is the homepage'
if __name__ == "__main__":
app.run(debug=True)
I thought
app.run(debug=True)
would work to clear the old data, but I doesn't and http://127.0.0.1:5000/ page keeps showing "Hello from Flask".
How do I fix this?
Just clear the cache in your browser and try running it again.
Here's how to clear your cache in some browsers:
Firefix->https://support.mozilla.org/en-US/kb/how-clear-firefox-cache
Chrome->https://support.google.com/accounts/answer/32050?co=GENIE.Platform%3DDesktop&hl=en
You can export the FLASK_ENV environment variable and set it to development before running the server
export FLASK_ENV=development
flask run
This worked for me.
Running the program in incognito tab will not cause this error. No need to clear caches also. See https://support.google.com/chrome/answer/95464?co=GENIE.Platform%3DAndroid&hl=en

Categories

Resources