from flask import Flask
app = flask(__name__)
#app.route("/")
def home():
return "Hello world"
if __name__ == "__main__":
app.run()
and in termianl send me this error
Traceback (most recent call last):
File "C:\Users\xd\Desktop\python-anashe\index.py", line 3, in <module>
app = flask(__name__)
NameError: name 'flask' is not defined
You're importing the name Flask from the module flask.
That means you'll need (note the capital F)
app = Flask(__name__)
instead of lower-case app = flask(__name__).
Related
from flask import flask
app = Flask(__name__)
#app.route('/'):
def index():
return 'hrllo'
I keep getting
Serving Flask app 'application.py' (lazy loading)
Environment: development
Debug mode: on
Usage: flask run [OPTIONS]
Try 'flask run --help' for help.
Error: While importing 'application', an ImportError was raised.
Try:
from flask import Flask #changed "flask" to "Flask"
app = Flask(__name__)
#app.route('/') #removed ":"
def index():
return 'hello'
app.run() #added this line to run your application
from flask import Flask, correction in your first line.
Remove the colon at the end of the line marking the route.
Also, you should do app.run() at the end of the code snippet.
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.
I am a very beginner in the flask environment..
this is main.py
from flask import Flask
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
class Helloworld(Resource):
def get(self):
return {"data": "Hello QQ"}
api.add_resource(Helloworld, "/helloworld")
if __name__ == "__main__":
app.run(debug=True)
text.py file
import requests
BASE = "http://127.0.0.1:5000/"
response = requests.get(BASE + "Helloworld")
print(response.json())
When I was run text.py, had these error..
Please tell me the error and why it is?
The route in your code says "/helloworld" but you are doing "/Helloworld" in your requests call and I'm pretty sure that part of your URL is case sensitive, at least in this example.
i'm trying to create a web server with Flask python library but there is something wrong because it keeps giving me the error when i run the file.
here is the code:
from flask import Flask, app
app = Flask(__name__)
#app_route("/")
def main():
return('welcome to my flask page')
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port="8090")
here is the error:
Traceback (most recent call last):
File "c:\Users\User\Desktop\Simone\Simone\Js Course\Python Web Server\web server.py", line 5, in <module>
#app_route("/")
NameError: name 'app_route' is not defined
Help me please!!!
The app you're importing from flask isn't what you expect (it's a module within Flask that contains flask code). You need to create an instance of Flask, and apply the route to that.
from flask import Flask
app = Flask(__file__) # add this
#app.route('/') # and use app.route instead of app_route
...
I have the following app which when I run using
flask run
seems to execute without error but when I perform python app.py gives me the following error:
➣ $ python app.py
Traceback (most recent call last):
File "app.py", line 14, in <module>
app.secret_key = os.environ['SECRET_KEY']
File "/Users/pkaramol/Workspace/second_flask/venv/bin/../lib/python3.7/os.py", line 678, in __getitem__
raise KeyError(key) from None
KeyError: 'SECRET_KEY'
#!/usr/bin/env python
import os
from flask import Flask
from flask_jwt import JWT, jwt_required
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy
import settings
from resources.item import Item, ItemList
app = Flask(__name__)
api = Api(app)
app.config.from_pyfile('settings.py')
app.secret_key = os.environ['SECRET_KEY']
db = SQLAlchemy(app)
if __name__ == "__main__":
print("Starting flask app...")
print(os.end['SECRET_KEY'])
db.create_all()
api.add_resource(Item, '/item/<string:name>')
api.add_resource(ItemList, '/items')
What is the difference in the two ways of running the flask app and why in the second case the environment is not rendered appropriately?
I am using python-dotenv to inject env vars from .env file
btw in the first case where the app starts without errors, I do not see the print statement I use for debug.
and if in the case of flask run the code below if __name__ == '__main__' is not called, how will I initialise my db by calling db.create_all()?
Replace app.secret_key assignment with arbitrary string.