Skip to content
This repository has been archived by the owner on Dec 15, 2022. It is now read-only.

Sourcery Starbot ⭐ refactored yanyongyu/CXmoocSearchTool #5

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
147 changes: 61 additions & 86 deletions api.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,40 +33,33 @@ async def cxmooc_tool(sess: requests.Session,

# 接口参数
index = yield
data = {}
for i in range(len(args)):
data['topic[%d]' % i] = args[i]

data = {'topic[%d]' % i: args[i] for i in range(len(args))}
# post请求
logging.info("Post to cxmooc_tool api.")
try:
res = sess.post(url, data=data, verify=False, timeout=5)
res.raise_for_status()
except requests.exceptions.RequestException as e:
logging.info("Request Exception appeared: %s" % e)
logging.info(f"Request Exception appeared: {e}")
answer = [{'topic': str(e), 'correct': ''}]
for each in args:
answer = []
answer.append({'topic': str(e),
'correct': ''})
yield answer
raise StopIteration

# 处理结果
logging.info("Processing result")
result = [[] for i in range(len(args))]
result = [[] for _ in range(len(args))]
for each in res.json():
for answ in each['result']:
temp = {}
temp['topic'] = answ['topic']
temp['correct'] = ''
temp = {'topic': answ['topic'], 'correct': ''}
for option in answ['correct']:
temp['correct'] = temp['correct'] + str(option['option'])
temp['correct'] += str(option['option'])
result[each['index']].append(temp)

for i in range(len(result)):
if index and i < index:
continue
logging.info("Yield question %s: %s" % (i+1, result[i]))
logging.info(f"Yield question {i + 1}: {result[i]}")
Comment on lines -36 to +62
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function cxmooc_tool refactored with the following changes:

index = yield result[i]
raise StopIteration

Expand Down Expand Up @@ -99,23 +92,19 @@ async def forestpolice(sess: requests.Session,
res = sess.post(url + args[i], data=data, verify=False, timeout=5)
res.raise_for_status()
except requests.exceptions.RequestException as e:
logging.info("Request Exception appeared: %s" % e)
answer = []
answer.append({'topic': str(e),
'correct': ''})
logging.info(f"Request Exception appeared: {e}")
answer = [{'topic': str(e), 'correct': ''}]
index = yield answer
continue

# 处理结果
logging.info("Processing result")
answer = []
temp = {}
temp['topic'] = args[i]
temp['correct'] = res.json()['data']
temp = {'topic': args[i], 'correct': res.json()['data']}
if temp['correct'] != '未找到答案':
answer.append(temp)

logging.info("Yield question %s: %s" % (i+1, answer))
logging.info(f"Yield question {i + 1}: {answer}")
Comment on lines -102 to +107
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function forestpolice refactored with the following changes:

index = yield answer

await asyncio.sleep(0.5)
Expand Down Expand Up @@ -150,21 +139,20 @@ async def jiuaidaikan(sess: requests.Session,
eventvalidation = selector.xpath(
'//*[@id="__EVENTVALIDATION"]/@value')
except requests.exceptions.RequestException as e:
logging.info("Request Exception appeared: %s" % e)
logging.info(f"Request Exception appeared: {e}")
index = yield
for i in range(len(args)):
if index and i < index:
continue
answer = []
answer.append({'topic': str(e),
'correct': ''})
yield answer
yield [{'topic': str(e), 'correct': ''}]
raise StopIteration

data = {}
data['__VIEWSTATE'] = viewstate
data['__EVENTVALIDATION'] = eventvalidation
data['ctl00$ContentPlaceHolder1$gen'] = '查询'
data = {
'__VIEWSTATE': viewstate,
'__EVENTVALIDATION': eventvalidation,
'ctl00$ContentPlaceHolder1$gen': '查询',
}

Comment on lines -153 to +155
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function jiuaidaikan refactored with the following changes:

for i in range(len(args)):
if index and i < index:
continue
Expand All @@ -176,24 +164,24 @@ async def jiuaidaikan(sess: requests.Session,
res = sess.post(url, data=data, verify=False, timeout=5)
res.raise_for_status()
except requests.exceptions.RequestException as e:
logging.info("Request Exception appeared: %s" % e)
answer = []
answer.append({'topic': str(e),
'correct': ''})
logging.info(f"Request Exception appeared: {e}")
answer = [{'topic': str(e), 'correct': ''}]
index = yield answer
continue

# 处理结果
logging.info("Processing result")
answer = []
selector = etree.HTML(res.text)
temp = {}
temp['topic'] = args[i]
temp['correct'] = selector.xpath('//*[@id="daan"]/text()')[0]
temp = {
'topic': args[i],
'correct': selector.xpath('//*[@id="daan"]/text()')[0],
}

if temp['correct'] != '未找到答案':
answer.append(temp)

logging.info("Yield question %s: %s" % (i+1, answer))
logging.info(f"Yield question {i + 1}: {answer}")
index = yield answer

await asyncio.sleep(0.5)
Expand All @@ -212,9 +200,7 @@ async def xuanxiu365(sess: requests.Session,

# 接口
url = "http://tiku.xuanxiu365.com/admin/admin/api.html"
header = {}
header['X-Requested-With'] = "XMLHttpRequest"

header = {'X-Requested-With': "XMLHttpRequest"}
Comment on lines -215 to +203
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function xuanxiu365 refactored with the following changes:

# 接口参数
index = yield
payload = {}
Expand All @@ -230,10 +216,8 @@ async def xuanxiu365(sess: requests.Session,
verify=False, timeout=5)
res.raise_for_status()
except requests.exceptions.RequestException as e:
logging.info("Request Exception appeared: %s" % e)
answer = []
answer.append({'topic': str(e),
'correct': ''})
logging.info(f"Request Exception appeared: {e}")
answer = [{'topic': str(e), 'correct': ''}]
index = yield answer
continue

Expand All @@ -242,11 +226,9 @@ async def xuanxiu365(sess: requests.Session,
res = res.json()
answer = []
if res['data']:
temp = {}
temp['topic'] = res['data']['title']
temp['correct'] = res['data']['content']
temp = {'topic': res['data']['title'], 'correct': res['data']['content']}
answer.append(temp)
logging.info("Yield question %s: %s" % (i+1, answer))
logging.info(f"Yield question {i + 1}: {answer}")
index = yield answer

await asyncio.sleep(0.5)
Expand Down Expand Up @@ -284,10 +266,8 @@ async def www150s(sess: requests.Session,
verify=False, timeout=5)
res.raise_for_status()
except requests.exceptions.RequestException as e:
logging.info("Request Exception appeared: %s" % e)
answer = []
answer.append({'topic': str(e),
'correct': ''})
logging.info(f"Request Exception appeared: {e}")
answer = [{'topic': str(e), 'correct': ''}]
Comment on lines -287 to +270
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function www150s refactored with the following changes:

index = yield answer
continue

Expand All @@ -302,7 +282,7 @@ async def www150s(sess: requests.Session,
if temp['topic'] == "查无此题,请您换一道题查询!":
break
answer.append(temp)
logging.info("Yield question %s: %s" % (i+1, answer))
logging.info(f"Yield question {i + 1}: {answer}")
index = yield answer

await asyncio.sleep(0.5)
Expand Down Expand Up @@ -336,11 +316,9 @@ async def wangkebang(sess: requests.Session,
res = sess.post(url, data=data, verify=False, timeout=5)
res.raise_for_status()
except requests.exceptions.RequestException as e:
logging.info("Request Exception appeared: %s" % e)
logging.info(f"Request Exception appeared: {e}")
for each in args:
answer = []
answer.append({'topic': str(e),
'correct': ''})
answer = [{'topic': str(e), 'correct': ''}]
Comment on lines -339 to +321
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function wangkebang refactored with the following changes:

yield answer
raise StopIteration

Expand All @@ -349,17 +327,19 @@ async def wangkebang(sess: requests.Session,
res.encoding = 'utf-8'
answer = []
selector = etree.HTML(res.text)
temp = {}
temp['topic'] = selector.xpath(
'/html/body/div[3]/div[1]/div/span[1]/strong/text()'
)[0].lstrip(" 题目:\n")
temp = {
'topic': selector.xpath(
'/html/body/div[3]/div[1]/div/span[1]/strong/text()'
)[0].lstrip(" 题目:\n")
}

temp['correct'] = selector.xpath(
'/html/body/div[3]/div[1]/div/span[2]/strong/text()'
)[0].lstrip(" 答案:\n")
if temp['topic'] != '啊哦暂无该题':
answer.append(temp)

logging.info("Yield question %s: %s" % (i+1, answer))
logging.info(f"Yield question {i + 1}: {answer}")
index = yield answer

await asyncio.sleep(0.5)
Expand Down Expand Up @@ -597,21 +577,19 @@ async def wangkebang(sess: requests.Session,
async def cmd():
# 获取所有api
api_list = {}
for each in globals().keys():
for each, fn in globals().items():
if each.startswith('_'):
continue
fn = globals()[each]
if callable(fn):
if getattr(fn, '__annotations__', None):
api_list[each] = fn
if callable(fn) and getattr(fn, '__annotations__', None):
api_list[each] = fn
Comment on lines -600 to +584
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function cmd refactored with the following changes:


args = sys.argv[1:]
if not args or "-h" in args:
print("超星查题助手\n\tpython api.py [-json] [-api=] -text=\nusage:")
print("\t-h\tPrint help")
print("\t-json\tReturn json data at last")
print("\t-api\tUsing the specified api\n\t\tapi list:")
for each in api_list.keys():
for each in api_list:
print("\t\t\t%s" % each)
print("\t-text\tquestion(-text can be used more than one time)")
else:
Expand All @@ -632,15 +610,15 @@ async def cmd():
elif each.startswith("-text="):
text.append(each[6:])
else:
ValueError("Unknow option %s. Use -h for help"
% each.split("=")[0])
ValueError(f'Unknow option {each.split("=")[0]}. Use -h for help')

# 获取答案
answer = [[] for i in range(len(text))]
answer = [[] for _ in range(len(text))]
if not search:
for each in api_list.keys():
remain = [text[i] for i in range(len(text)) if not answer[i]]
if remain:
for each in api_list:
if remain := [
text[i] for i in range(len(text)) if not answer[i]
]:
generator = api_list[each](*remain)
await generator.asend(None)
for i in range(len(text)):
Expand All @@ -649,16 +627,13 @@ async def cmd():
continue
else:
answer[i] = result
else:
if text:
generator = search(*text)
await generator.asend(None)
for i in range(len(text)):
result = await generator.asend(None)
if not result or not result[0]['correct']:
continue
else:
answer[i] = result
elif text:
generator = search(*text)
await generator.asend(None)
for i in range(len(text)):
result = await generator.asend(None)
if result and result[0]['correct']:
answer[i] = result

if not JSON:
print(answer)
Expand Down
33 changes: 18 additions & 15 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ def _configure_frame(event):
if len(self.text) <= 3:
self.root.geometry('%dx%d' % (600, 35 + 70*len(self.text)))
canvas.config(height=frame_in.winfo_reqheight())
elif len(self.text) > 3:
else:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function App.show._configure_frame refactored with the following changes:

self.root.geometry('%dx%d' % (600, 35 + 70*3))
canvas.config(height=210)

Expand Down Expand Up @@ -439,9 +439,11 @@ def scan_cx(self):

print(question)

raw_question = [each[each.index("】") + 1:]
for each in question if each.find("】") != -1]
return raw_question
return [
each[each.index("】") + 1 :]
for each in question
if each.find("】") != -1
]
Comment on lines -442 to +446
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function App.scan_cx refactored with the following changes:


def scan_zhs(self):
clipboard_text = self.root.clipboard_get().strip()
Expand All @@ -454,11 +456,12 @@ def scan_zhs(self):

question = html or zhs_text

raw_question = [question[i + 1]
for i in range(len(question) - 1)
if question[i].find("】") != -1
if question[i].find(r")") != -1]
return raw_question
return [
question[i + 1]
for i in range(len(question) - 1)
if question[i].find("】") != -1
if question[i].find(r")") != -1
]
Comment on lines -457 to +464
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function App.scan_zhs refactored with the following changes:


def start_search(self):
"开始搜索,显示答案窗口"
Expand Down Expand Up @@ -532,14 +535,14 @@ async def search(self, frame_list):
if self.api_on[api].get():
generator_list[api] = self.api_list[api](self.sess, *text)
# 启动迭代器
logging.info("Active generator %s" % api)
logging.info(f"Active generator {api}")
await generator_list[api].asend(None)

# 查询答案
for i in range(len(text)):
label = frame_list[i].children['!text']
label.configure(state="normal")
for generator in generator_list.keys():
for generator in generator_list:
Comment on lines -535 to +545
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function App.search refactored with the following changes:

label.insert(END, f"查询中。。。使用源{generator}\n")
label.configure(state="disable")
try:
Expand Down Expand Up @@ -661,7 +664,7 @@ async def scan_release(self, silence):
res = self.sess.get(URL)
res.raise_for_status()
except requests.exceptions.RequestException as e:
logging.info("Request Exception appeared: %s" % e)
logging.info(f"Request Exception appeared: {e}")
Comment on lines -664 to +667
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function App.scan_release refactored with the following changes:

showinfo(title="查题助手",
message="检查更新失败了!")
else:
Expand All @@ -679,9 +682,9 @@ async def scan_release(self, silence):
now.append('0')
for i in range(len(now)):
if latest[i] > now[i]:
if askyesno(title="查题助手",
message="发现新版本%s!是否前去更新?"
% info['tag_name']):
if askyesno(
title="查题助手", message=f"发现新版本{info['tag_name']}!是否前去更新?"
):
webbrowser.open(info['html_url'])
if info['assets'][0]['name'].endswith('.exe'):
webbrowser.open(
Expand Down