问题描述
使用import
:
- 将python脚本(例如
website_generator.py
)生成的内容包装到函数中。 - 将其放置在与
app.py
或相同的目录中flask.py
。 - 用
from website_generator import function_nam
e在flask.py
- 使用运行它
function_name()
你可以使用其他功能,例如subprocess.callet
等。尽管他们可能不会给你答复。
使用示例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)
解决方法
我有一个Flask
脚本,可以创建网站并动态打印一些数据。-打印的数据应来自另一个python脚本。
我目前面临的问题是,如果我将执行python脚本的行放在执行Flask
应用程序的行之前,它将运行Python脚本而不运行Flask
;反之亦然。
Python脚本:
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脚本(注意:价格应为其他脚本的“解析”变量):
# 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)