python - Flask 蓝图将对象传递到另一个文件

标签 python flask

我正在使用 python selenium 来创建一个 Web 服务,当调用它时,它将执行一些到页面的指令,但问题是使用 Flask 蓝图将“驱动程序”类传递到另一个页面。

main.py

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options as chrome_options
from classes.send_message import send_message
from flask import Flask
from flask_restful import Resource, Api
from flask import request

app = Flask(__name__)
api = Api(app)

app.register_blueprint(send_message)

if __name__ == '__main__':

    logging.info('START APP')

    options = webdriver.ChromeOptions() 
    options.add_argument("user-data-dir=C:\\myuserpath........")
    driver = webdriver.Chrome(executable_path="chromedriver.exe", chrome_options=options)

    driver.get("https://example.com")

    app.run(host='192.168.50.1', port='11111',debug=False)

发送消息.py

from flask import Blueprint
#from flask import current_app as app    
send_message = Blueprint('send_message', __name__)

@send_message.route("/SendPostMessage")
def sendMessage():
    side_panel = driver.find_element_by_id('menutop') # error here!!!

错误:

  File "C:\python36\lib\site-packages\flask\app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\rararara\classes\send_message.py", line 8, in sendMessage
    side_panel = driver.find_element_by_id('menutop')
NameError: name 'driver' is not defined

最佳答案

您可以使用应用程序对象作为上下文:

...
driver.get("https://example.com")
app.driver = driver
app.run(host='192.168.50.1', port='11111',debug=False)

然后

from flask import current_app as app
...
@send_message.route("/SendPostMessage")
def sendMessage():
    side_panel = app.driver.find_element_by_id('menutop')

关于python - Flask 蓝图将对象传递到另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44724633/

相关文章:

Python 使用 PIL 调整动画 gif 的大小

python - 循环运行 scrapy 任务

python - 如何将字符串转换为字典转义python中的特殊字符

python - 在 flask/gunicorn 中初始化应用程序的位置

python - Html 找不到 flask url

python - 在 Django 中使用 AJAX 更新数据库

Python 列表索引并返回项目

python - 使用 apache mod_wsgi 部署基于 flask 的应用程序时的 MySQL 连接

python - 如何通过超链接或Web界面从中运行.py文件?

python - 自定义 Flask-WTF 或 WTForms