im trying to get A Value from a Python Script which looks like that:
from flask import Flask, jsonify
app = Flask(__name__)
#app.route('/', methods = ['GET'])
def index():
return jsonify({"greetings" : "Hi this is Python"})
if __name__ == '__main__':
app.run(debug = True)
After launichg im getting the following Output:
C:\Users\finn1\PycharmProjects\FLASK_FLUTTER_APP\venv\Scripts\python.exe C:/Users/finn1/PycharmProjects/FLASK_FLUTTER_APP/main.py
* Serving Flask app "main" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
* Debugger is active!
* Debugger PIN: ***-***-***
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Thei i imported the http libary in Flutter like that :
import 'package:http/http.dart';
Then i tried to get the Data with "http.get":
child: IconButton(
icon: new Icon(
Icons.settings,
),
onPressed: () async {
final response = await http.get("http://127.0.0.1:5000/");
But i am getting the following Error when launching my App:
Error: The getter 'http' isn't defined for the class '_HomepageState'.
- '_HomepageState' is from 'package:what_todo/screens/homepage.dart' ('lib/screens/homepage.dart').
Try correcting the name to the name of an existing getter, or defining a getter or field named 'http'.
final response = await http.get("http://127.0.0.1:5000/");
Thank You for Help!
Try to use import 'package:http/http.dart' as http;
package example
Related
I have been using the following python 3 script in a CDSW session which run just fine as long as the session is not killed.
I am able to click on the top-right grid and select my app
hello.py
from flask import Flask
import os
app = Flask(__name__)
#app.route('/')
def index():
return 'Web App with Python Flask!'
app.run(host=os.getenv("CDSW_IP_ADDRESS"), port=int(os.getenv('CDSW_PUBLIC_PORT')))
I would like this app to run 24/7, so instead of using a Session or scheduling a job that never ends, I would like to create a CDSW Application so that it doesn't stop.
This is the settings on my application:
Logs:
from flask import Flask
import os
app = Flask(__name__)
#app.route('/')
def index():
return 'Web App with Python Flask!'
app.run(host=os.getenv("CDSW_IP_ADDRESS"), port=int(os.getenv('CDSW_PUBLIC_PORT')))
* Serving Flask app "__main__" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
OSError: [Errno 98] Address already in use
I tried to change the port from CDSW_PUBLIC_PORT to CDSW_APP_PORT but it ends up the same.
As it mentions here maybe you need to change this line of code
app.run(host=os.getenv("CDSW_IP_ADDRESS"), port=int(os.getenv('CDSW_PUBLIC_PORT')))
to this
app.run(host="127.0.0.1", port=int(os.environ['CDSW_APP_PORT']))
Hope it works!
I'm building a Flask application that needs to access an initialized class across requests. The below POST request to the Flask server says that the global variable ex is of type None, despite it being initialized and reassigned to the Engine class in the main on startup. Why is this?
ex = None #Storing the executable so that it can be accessed
flask_app = Flask(__name__)
flask_app.debug = True
#flask_app.route('/reach_engine', methods = ['POST'])
def result():
global ex
print(ex.txt) #Prints type error, saying that ex is of type None (this is the problem)
class Engine:
def __init__(self):
super(Engine, self).__init__()
self.txt = 'The real Engine'
def startApp():
global ex
ex = Engine()
if __name__ == '__main__':
#Start a thread that will run the main app
t = threading.Thread(target=startApp)
t.daemon = True
t.start()
# Start the flask app
print(rd_info + "Intializing Flask application")
flask_app.run('0.0.0.0', '1000', debug=True,
threaded=True, use_reloader=False)
Try to use #flask_app.before_first_request and then create the thread. I leave you this link if you want more details: Global variable is None instead of instance - Python
I ran your code after adding the missing imports, setting rd_info, and changing the port to 5000 (because ports below 1024 are privileged ports on many systems)
$ python stackoverflow.py
random-Intializing Flask application
* Serving Flask app "stackoverflow" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
then
$ curl --request POST --data '' http://0.0.0.0:5000/reach_engine
caused
The real Engine
10.0.2.2 - - [10/Jul/2020 17:31:18] "POST /reach_engine HTTP/1.1" 500 -
Traceback (most recent call last):
...
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
plus a spew of Flask/Werkzeug debug info on the curl side. I expected the TypeError, given the lack of return in the route. Still, this proves that the thread is running.
This was on Ubuntu 18.04 with Python 3.6.9.
This has now been resolved. In the original code, there was an intentional for loop in the initialization of the engine, causing the global variable ex never to be fully assigned. (Note for others finding this)
This question already has answers here:
__del__ on exit behavior
(1 answer)
I don't understand this python __del__ behaviour
(8 answers)
Closed 2 years ago.
I have the following, seemingly easy, issue which I cannot figure out.
I made a short, self-containing example below:
from flask import Flask
class MyFlask(Flask):
def __init__(self, name):
super().__init__(name)
print(f'Initialising Flask app {id(self)}')
def __del__(self):
print(f'Deleting Flask app {id(self)}')
if __name__ == "__main__":
app = MyFlask(__name__)
app.run(host='0.0.0.0', port=5000, debug=True)
When one runs this, you will see two instances of MyFlask being initialized, but only one being destroyed. I know why there are two calls to the init method (the way Werkzeug works), but why is only one destroyed?
See the sample output below:
(venv) D:\Onedrive\Documents\Projects\FlaskReloader>python example.py
Initialising Flask app 1944027544880
* Serving Flask app "example" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
Initialising Flask app 2213899877680
* Debugger is active!
* Debugger PIN: 247-475-647
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
Deleting Flask app 1944027544880
Any ideas? Thanks!
I think it cause by the override of Flask.__del__
Call super on that __del__ or don't override
print(f'Deleting Flask app {id(self)}')
super().__del__(self)
I have written a Flask App as follows:
import logging
from flask import Flask, jsonify
from mongo import Mongo
app = Flask(__name__)
app.config.from_object("config.ProductionConfig")
# routes to a particular change and patch number
#app.route("/<project>/")
def home(project):
app.logger.info('testing info log')
Mongo_obj = Mongo(ip=app.config["DB_HOST"], port=app.config["DB_PORT"],
username=app.config["DB_USERNAME"],
.....................
if __name__ == '__main__':
app.run(host = '0.0.0.0', port = '5000')
Now, the problem I face is, when I look at the logs of the Flask application, all I see is the following:
* Serving Flask app "service" (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
172.16.40.189 - - [01/Oct/2019 14:44:29] "GET /abc HTTP/1.1" 200 -
172.16.11.231 - - [01/Oct/2019 14:44:29] "GET /abc HTTP/1.1" 200 -
............
Is there something specific that needs to be done in order to see the log message? Do I need to run the Flask App in debug mode?
If not in debug mode the default log level is WARNING. That's why you don't see your logs. If you'd like your logs to contain INFO level ones you must set it within the logger, eg:
app = Flask(__name__)
app.logger.setLevel(logging.INFO)
This is how I set log levels in our app. I use the create_app function to create a flask app with error handling logging & other necessary configurations. Here is the snippet:
from flask import Flask
import logging
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__)
app.logger.setLevel(logging.ERROR)
# Test Log levels
app.logger.debug("debug log info")
app.logger.info("Info log information")
app.logger.warning("Warning log info")
app.logger.error("Error log info")
app.logger.critical("Critical log info")
return app
app = create_app()
Output show only error and lower logs are visible for now
* Restarting with stat
[2022-12-12 17:38:39,375] ERROR in __init__: Error log info
[2022-12-12 17:38:39,375] CRITICAL in __init__: Critical log info
I'm trying to set-up an application which will receive HTTP GET's and POST's using python and flask-restful. The problem that I'm getting is that when I start the application I see that there are two instances of a queue being generated. I would like you to help me understand why?
Application output (terminal):
<queue.Queue object at 0x10876fdd8>
* Serving Flask app "main" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
<queue.Queue object at 0x10ce48be0>
* Debugger is active!
* Debugger PIN: 292-311-362
Python code (ran with the following command python -m main):
import json
from flask import Flask, request
from flask_restful import Resource, Api, reqparse
import requests
import os
import threading
import queue
import sys
app = Flask(__name__)
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument("endpoint")
queue = queue.Queue()
base_path = os.path.dirname(os.path.realpath(__file__))
config = Json_Parser().get_json_object(base_path + "path")
consumer = Consumer(config, queue)
t1 = threading.Thread(target=consumer.consume)
t1.start()
class Interaction(Resource):
def get(self):
self.create_interaction()
thread_queue = consumer.get_queue()
output = thread_queue.get()
return output
api.add_resource(Interaction, '/interaction')
if __name__ == '__main__':
print(queue)
app.run(debug=True)
With the help of #Richar de Wit I changed the following line:
app.run(debug=True)
to:
app.run(debug=True, use_reloader=False)
to prevent the debugger to instantiate two queues thus giving issues later on.
The problem is referenced in this question:
Why does running the Flask dev server run itself twice?