How can I run a python script from within Flask

Jack022

I have a Flask script which creates a website and prints some data dynamically. - The data which it prints should come from another python script.

The current problem that I'm facing is that if I put the line that executes the python script before the line that executes the Flask app, it will run the Python script without running Flask; and vice versa.

Python script:

import websocket
from bitmex_websocket import Instrument
from bitmex_websocket.constants import InstrumentChannels
from bitmex_websocket.constants import Channels
import json

websocket.enableTrace(True)

sells = 0
buys = 0


channels = [
    InstrumentChannels.trade,
]


XBTUSD = Instrument(symbol='XBTUSD',
                    channels=channels)
XBTUSD.on('action', lambda msg: test(msg))


def test(msg):
    parsed = json.loads(json.dumps(msg))


    print(parsed)

XBTUSD.run_forever()

Flask script (NB: price should be the variable 'parsed' from the other script):

# Start with a basic flask app webpage.
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
import requests, json
import time

__author__ = 'slynn'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

#turn the flask app into a socketio app
socketio = SocketIO(app)

#random number Generator Thread
thread = Thread()
thread_stop_event = Event()

class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()

    def randomNumberGenerator(self):
        while not thread_stop_event.isSet():
            socketio.emit('newnumber', {'number': parsed}, namespace='/test')
            sleep(self.delay)

    def run(self):
        self.randomNumberGenerator()


@app.route('/')
def index():
    #only by sending this page first will the client be connected to the socketio instance
    return render_template('index.html')

@socketio.on('connect', namespace='/test')
def test_connect():
    # need visibility of the global thread object
    global thread
    print('Client connected')

    #Start the random number generator thread only if the thread has not been started before.
    if not thread.isAlive():
        print("Starting Thread")
        thread = RandomThread()
        thread.start()

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')


if __name__ == '__main__':
    socketio.run(app)
Julian Camilleri

Using import:

  • Wrap what the python script (e.g. website_generator.py) is generating into a function.
  • Place it in the same directory as your app.py or flask.py.
  • Use from website_generator import function_name in flask.py
  • Run it using function_name()

You can use other functions such as subprocess.call et cetera; although they might not give you the response.

Example using import:

from flask import Flask
import your_module # this will be your file name; minus the `.py`

app = Flask(__name__)

@app.route('/')
def dynamic_page():
    return your_module.your_function_in_the_module()

if __name__ == '__main__':
    app.run(host='0.0.0.0', port='8000', debug=True)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How can I run a python script from within Flask

From Java

How can I run a Python script from Ubuntu Dash?

From Dev

How can I run a Python script from Ubuntu Dash?

From Dev

How can I get the username from a python script run with pkexec?

From Dev

How do I run an instance of Elasticsearch from within a Flask python application?

From Dev

How can I run Kotlin-Script (.kts) files from within Kotlin/Java?

From Dev

Windows can't run python script from within eclipse

From Dev

How can I run a Python 3 script?

From Dev

How to run Python Flask within a Docker container

From Java

How can I run nodemon from within WebStorm?

From Dev

How can I test if a program is running from within a script

From Dev

When attempting run a python script from within another python script, I get 'permission denied'!

From Dev

How can I create a separate namespace within a Python script?

From Dev

How do I run a scipt from within Python on windows/dos?

From Dev

Can I access the originating $USER variable from within a script run with `sudo`?

From Dev

How can I to run php script from powershell-commandline?

From Dev

How can I run a kwin script from the command line?

From Dev

How do you run a Python script from within Notepad++ but using powershell and in the directory of the script?

From Dev

How can I run my python code as a script

From Dev

How can I get an html for to run a python script on submit?

From Dev

How do I get the path of a script(python) from my qt project, so I can run it during execution?

From Dev

How do I run Python script from a subdirectory?

From Java

Can I ask a browser to not run <script>s within an element?

From Dev

How can I return a datetime from route with python flask

From Dev

How can I get the source directory of a Bash script from within the script itself?

From Dev

How can I suppress output of a bash script from within the script itself?

From Dev

How can I recursively find directories and parse them into python script call within bash script?

From Dev

How to run Python script to run daily using apscheduler with flask?

From Dev

Why can't I use 'sudo su' within a shell script? How to make a shell script run with sudo automatically

Related Related

  1. 1

    How can I run a python script from within Flask

  2. 2

    How can I run a Python script from Ubuntu Dash?

  3. 3

    How can I run a Python script from Ubuntu Dash?

  4. 4

    How can I get the username from a python script run with pkexec?

  5. 5

    How do I run an instance of Elasticsearch from within a Flask python application?

  6. 6

    How can I run Kotlin-Script (.kts) files from within Kotlin/Java?

  7. 7

    Windows can't run python script from within eclipse

  8. 8

    How can I run a Python 3 script?

  9. 9

    How to run Python Flask within a Docker container

  10. 10

    How can I run nodemon from within WebStorm?

  11. 11

    How can I test if a program is running from within a script

  12. 12

    When attempting run a python script from within another python script, I get 'permission denied'!

  13. 13

    How can I create a separate namespace within a Python script?

  14. 14

    How do I run a scipt from within Python on windows/dos?

  15. 15

    Can I access the originating $USER variable from within a script run with `sudo`?

  16. 16

    How can I to run php script from powershell-commandline?

  17. 17

    How can I run a kwin script from the command line?

  18. 18

    How do you run a Python script from within Notepad++ but using powershell and in the directory of the script?

  19. 19

    How can I run my python code as a script

  20. 20

    How can I get an html for to run a python script on submit?

  21. 21

    How do I get the path of a script(python) from my qt project, so I can run it during execution?

  22. 22

    How do I run Python script from a subdirectory?

  23. 23

    Can I ask a browser to not run <script>s within an element?

  24. 24

    How can I return a datetime from route with python flask

  25. 25

    How can I get the source directory of a Bash script from within the script itself?

  26. 26

    How can I suppress output of a bash script from within the script itself?

  27. 27

    How can I recursively find directories and parse them into python script call within bash script?

  28. 28

    How to run Python script to run daily using apscheduler with flask?

  29. 29

    Why can't I use 'sudo su' within a shell script? How to make a shell script run with sudo automatically

HotTag

Archive