Launch flask python file from main python file - python

I have a flask python file that i want to open when i start the main python file.
main python file
start flask python file
continue with it's own independent processes (threading)
Which solution to take since i do not want the execution of the flask app to hinder the performance of the later processes. Not sure if i should do a subprocess or exec file?
both files are pretty independent of each other.

if I understood correctly, you can create a daemon thread for flask and continue with the execution of main program.
If you have a independent_module.py like this:
# independent_module.py
# your independent functions
def start():
pass
Then your main file would look something like this:
# main.py file
import threading
from flask import Flask
import main
app = Flask(__name__)
#app.route("/health")
def health():
return "OK"
#app.route("/ping")
def ping():
return "Et. Voila!!"
def run_server_api():
app.run(host='0.0.0.0', port=8080)
def main():
flask_thread = threading.Thread(target=run_server_api, daemon=True)
flask_thread.start()
# continue with your main program functions
independent_module.start()
if __name__ == "__main__":
# execute main
main()
You can simply execute python main.py

Related

Python Tkinter with Flask API and Subprocess

Could I run a function from another python file inside subprocess?
I use pyinstaller to convert the tkinter to an executable file. As much as possible I would like to deploy/run the .exe file to another computer without installing python.
#gui.py
from tkinter import *
import os
import subprocess
root = Tk()
root.geometry("300x150")
def backendStart():
subprocess.Popen(["test.py"], shell=True)
label = Label(root, text="Connection String", fg="grey", font=("Helvetica", 15, "bold"))
label.pack(pady=(0,3))
root.after_idle(backendStart)
root.mainloop()
Here is my sample app.py
from flask import Flask, jsonify
from flask_restful import Api, Resource
from flask_socketio import SocketIO, emit
from flask_cors import CORS
import random
from connection import cursor
app = Flask(__name__)
app.config["DEBUG"] = True
api = Api(app)
CORS(app)
socketio = SocketIO(app, cors_allowed_origins="*")
#socketio.on("connect")
def ClientConnection():
print("Client is Connected")
#socketio.on("realtime", namespace="/sample-socket")
def RealTimeData():
while True:
num = random.randint(1, 100)
emit("data", {"random": num})
socketio.sleep(1)
#socketio.on("disconnect")
def ClientDisconnected():
print("client has disconnected")
class HomePage(Resource):
def get(self):
return jsonify(msg="hello world")
api.add_resource(HomePage, "/")
if __name__ == '__main__':
socketio.run(app, host="192.168.0.109", port=5000)
Currently I made a .spec file for configurating the names, logo, and files/libs included. The .exe file work as long as I pasted the app.py inside the build folder along with the connection.py for the database.
But with this set up I do need to install python along with the libraries I used for the app.py and connection.py
Could I run a function from another
python file inside subprocess?
you can use multiprocessing.Process()
Edit:
For an expert's answer, see here
Alternate solution:
Lets say you want to run app.exe (which is app.py), you can pack all of them into one folder (--onedir) and put those exe's and pyd's subfolders.... together, like
gui
----flask (and other folders)
----*.pyd
----app.exe
----gui.exe
----python39.dll
you will need a custom spec file to do that.
see https://pyinstaller.readthedocs.io/en/stable/spec-files.html#multipackage-bundles

Flask Python - basic program does not work

I wrote this super basic application. It runs but does not do a thing:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def Index():
return "<h1>Hello!</h1>"
if __name__ == "__name__":
app.run(debug=True)
The console shows:
C:\Users\TalT\PycharmProjects\FlaskBeginners\venv\Scripts\python.exe
C:/Users/TalT/PycharmProjects/FlaskBeginners/MyFirstWebPage.py
Process finished with exit code 0
I work on Win10, PyCharm 2019.3.3 and Python 3.7 .
I don't understand where is the problem? Is it a python issue or maybe project configuration?
Your problem is:
if __name__ == "__name__":
Must change to:
if __name__ == '__main__':
To start a flask app you have 2 easy different ways.
1. Rename your main file to app.py or wsgi.py and go to path of the file in terminal and type flask run. In this way, if you want to run app in debug mode, In the same path, type set FLASK_ENV=development in terminal (Windows) and then write flask run.
Tip: In this way, you must delete the following code from your project:
if __name__ == '__main__':
app.run()
2. Write your code in a python file (name is not matter) for example with main.py name write like this:
from flask import Flask
app = Flask(__name__)
app.config['DEBUG']=True
#app.route('/')
def Index():
return '<h1>Hello!</h1>'
if __name__ == '__main__':
app.run()
And run the application by running this command in the path of your file: python main.py . Remember, add this code app.config['DEBUG']=True only if you want to run your code in debug mode.

Close python script and reopen it

i have a python script that i want to close console and then execute again the script from the beginning. Can you help me with this?
I need to close it when i execute a function on the script. Then reopen the file so it's ready again for doing something.
You should import your script instead. You can import python files from same directory. An example:
rerun.py:
def print_stuff():
print('stuff')
runner.py:
from rerun import print_stuff
print_stuff()
Use flask. It is made for this. Go take a look at http://flask.pocoo.org/docs/1.0/quickstart/.
from flask import Flask
app = Flask(__name__)
#app.route('/')
def some_function():
print('do stuff here')

python how to create json file in runtime?

i'm trying to code in multithreading,one of my thread supposed to create a file ,and other thread should use the file. the thread sync well.
the problem is that the file object writing into the disk when the code finish or when i'm press the terminate button (i'm using PyCharm pro).
little example:
1. i tried to use service that call other script test1 , but it doesn't work well.
i supposed that if test1 will create the file , he can do that many times as long as service didn't finish the running .
i tried to create a file and then to use while true- to imagine that the code is keep running
my question is how can i force my code to create the file before my main code finish?
service.py
import time
import runpy
import test1
def anotherChance(global_vars=None, local_vars=None):
with open("test1.py") as f:
code = compile(f.read(), "test1.py", 'exec')
exec(code, global_vars, local_vars)
def service_func():
print('service func')
print('while loop')
while True:
print(1234)
time.sleep(5)
test1.some_func()
if __name__ == '__main__':
#exec(open("test1.py").read()) ##1 another wrong sol
#anotherChance() ##2 another wrong sol
#service_func()
test1.some_func()
service_func()
test1.py
import os
def tempreding ():
with open('betext_file.json', 'w') as file:
file.write('helloo')
print(file.fileno())
def some_func():
print('in test 1, unproductive')
#infile=open('abcs.json','w')
#infile.write('aabbcc')
tempreding()
if __name__ == '__main__':
#print("I am a test")
#print(" I do nothing .")
some_func()

Flask app does not use routes defined in another module

I can't get it to work to use one module that creates the Flask application object and runs it, and one module that implements the views (routes and errorhandlers). The modules are not contained in a Python package.
app.py
from flask import Flask
app = Flask('graphlog')
import config
import views
if __name__ == '__main__':
app.run(host=config.host, port=config.port, debug=config.debug)
views.py
from app import app
#app.route('/')
def index():
return 'Hello!'
config.py
host = 'localhost'
port = 8080
debug = True
I always get Flask's default "404 Not Found" page. If I move the contents of view.py to app.py however, it works. What's the problem here?
You have four modules here:
__main__, the main script, the file you gave to the Python command to run.
config, loaded from the config.py file.
views, loaded from the views.py file.
app, loaded from app.py when you use import app.
Note that the latter is separate from the first! The initial script is not loaded as app and Python sees it as different. You have two Flask objects, one referenced as __main__.app, the other as app.app.
Create a separate file to be the main entry point for your script; say run.py:
from app import app
import config
if __name__ == '__main__':
app.run(host=config.host, port=config.port, debug=config.debug)
and remove the import config line from app.py, as well as the last two lines.
Alternatively (but much uglier), use from __main__ import app in views.py.

Categories

Resources