forked from ronething/xiudong-selenium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
99 lines (81 loc) · 2.78 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# coding=utf-8
from flask import Flask, g, request
from selenium import webdriver
from driver import create_instance, goto_login_url, quit_driver
from concurrent.futures import ThreadPoolExecutor
def create_app(driver, pool):
app = Flask(__name__)
@app.before_request
def inject_middleware(): # 注入一些全局变量
# 自动切换当前窗口
print("切换窗口")
try:
print(driver.window_handles)
driver.switch_to.window(driver.window_handles[0]) # 切换到第一个窗口
except Exception as e:
print(f'切换窗口失败, err: {e}')
errmsg = str(e)
if 'chrome not reachable' in errmsg:
# 重新启动 driver,这里可以做一个 reload driver func,单例 driver
pass
# 注入 selenium driver
g.driver = driver
g.pool = pool
init_router(app)
# init_custom_router(app)
return app
def init_router(app: Flask):
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
@app.route('/login')
def login_website():
# 登录网站
driver: webdriver.Chrome = g.driver
pool: ThreadPoolExecutor = g.pool
pool.submit(goto_login_url, driver=driver) # 不需要获取结果
# goto_login_url(driver)
return 'login OK'
@app.route('/buy', methods=['GET', 'POST'])
def buy():
# 通用抢票 api, 需要传入 ticketId 以及 event
# 可选项: cron_time 表示是否定时
# ticketNum 表示 购票数量
# example: ?event=123&ticketId=456
driver: webdriver.Chrome = g.driver
pool: ThreadPoolExecutor = g.pool
ticketId = request.args.get('ticketId')
event = request.args.get('event')
if not ticketId or not event:
return 'ERROR'
ticketNum = request.args.get('ticketNum')
if not ticketNum:
ticketNum = 1
print('ticketNum = ', ticketNum)
# 是否需要选择观演人 以及几个人
need_select = request.args.get('need_select', False)
select_num = request.args.get('select_num', 1)
cron_time = request.args.get('cron_time')
if not cron_time:
cron = False
else:
cron = True
print(f'cron_time is {cron_time}, 是否是定时配置: {cron}')
# 提交任务
pool.submit(
create_instance,
driver,
ticketId,
event,
ticketNum,
cron_time,
need_select,
select_num,
)
return 'buy OK'
@app.route('/quit')
def quit_website():
# 退出
driver: webdriver.Chrome = g.driver
quit_driver(driver)
return '关闭 driver OK'