首页

基本教程

视频教程

其它

https://github.com/paradoxxxzero/butterfly
https://github.com/finiteloop/blog

##d

网络

##d

大型教程

参考

系列教程

文章

实战聊天室

系列教程

文章

实战聊天室

sd

Python3爬取某教育平台题库保存为Word文档

参考

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

#!/usr/bin/python
#-*-encodeing:utf-8-*-
import tornado.web
import tornado.ioloop
import tornado.options
import multiprocessing
from tornado.options import define,options
import os,sys

define("port", default=9000, help="run on the given port", type=int)

class BaseHandler(tornado.web.RequestHandler):
def get_current_user(self):
return self.get_secure_cookie('user')
def get_template_path(self):
return os.path.join(os.path.dirname(__file__),'templates')


class MainHandler(BaseHandler):
@tornado.web.asynchronous
@tornado.web.authenticated
def get(self):
name=tornado.escape.xhtml_escape(self.current_user)
self.write('Hello'+self.current_user)
self.finish()

class LoginHandler(BaseHandler):
def lower(self,string):
return string.lower()

def get(self):
self.write('''
<html>
<head><title>MyDemo</title></head>
<body>
<form action='/login' method='post'>
Username:<input type='text' name='username'/>
Password:<input type='password' name='password'/>
<input type='submit' value='Submit'/>
</form>
</body>
</html>
'''),

def post(self):
if not self.request.headers.get('Cookie'):
self.write('Please enable your Cookie option of your broswer.')
return
self.set_secure_cookie('user',self.get_argument('username'),expires_days=1)
self.redirect('/')


settings={
'static_path':os.path.join(os.path.dirname(__file__),'static'),
'cookie_secret':'F/hsxF7kTIWGO1F6HrH78Rf4bMRe5EyFhjtReh6x+/E=',
'login_url':'/login',
'debug':True,
}

app=tornado.web.Application([
(r'/',MainHandler),
(r'/login',LoginHandler),
],**settings)


if __name__ == '__main__':
tornado.options.parse_command_line()
def run(mid,port):
print "Process %d start" % mid
sys.stdout.flush()
app.listen(port)
tornado.ioloop.IOLoop.instance().start()
jobs=list()
for mid,port in enumerate(range(9010,9014)):
p=multiprocessing.Process(target=run,args=(mid,port))
jobs.append(p)
p.start()

微信公众号后台

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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
## -*- coding: utf-8 -*-
#coding=utf-8

import os
import time
import traceback
import json
import urllib
import urllib2
import hashlib
import threading

import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.autoreload
from tornado.options import define, options

import xml.etree.ElementTree as ET

import config
from wxhelper import WeixinHelper


# 导入日志 并进行配置
import logging
logging.basicConfig(
filename = os.getcwd() + "/web.log",
# format = "%(levelname)-10s %(asctime)s %(filename)s %(module)s %(funcName)s %(lineno)s %(message)s",
format = "%(levelname)-2s %(asctime)s %(filename)s %(lineno)s %(message)s",
level = logging.INFO
)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(levelname)-2s %(filename)s line:%(lineno)-2s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
# CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET

# server config
define("port", default=444, help="run on the given port", type=int)
define("debug", default=True, help="set debug mode", type=bool)


SessionMap = {}

class BaseHandler(tornado.web.RequestHandler):
def get_current_user(self):
session_id = self.get_secure_cookie('session_id')
if session_id and SessionMap.has_key(session_id):
data = SessionMap[session_id]
if data['over_time'] < int(time.time()):
del SessionMap[session_id]
self.set_secure_cookie('session_id', None)
return None
else:
return data
else:
return None

def __create_id(self):
new_id = session_id = lambda: hashlib.sha1('%s%s' % (os.urandom(16), time.time())).hexdigest()
return new_id()

def set_current_user(self, data):
session_id = self.get_secure_cookie('session_id')
if session_id is None:
id = self.__create_id()
self.set_secure_cookie('session_id', id)

SessionMap[session_id] = data

def set_default_headers(self):
self.set_header('Access-Control-Allow-Origin', '*')
self.set_header('Access-Control-Allow-Methods', 'POST, GET, METHODS, OPTIONS')
self.set_header('Access-Control-Max-Age', 1000)
self.set_header('Access-Control-Allow-Headers', '*')
# self.set_header('Content-type', 'application/json')



class IndexHandler(tornado.web.RequestHandler):
def get(self):
self.render('index.html')
# self.write('welcom view xue zhan dao di!!!')
# self.render('index.html',appId = appId, timestamp = timestamp, nonceStr=nonceStr, signature = signature)
# self.redirect('http://113.106.164.45:8081/UpdateRes/web/?n', permanent=True)
#


class OtherHtmlHandler(tornado.web.RequestHandler):
def get(self, page):
pagename= page + '.html'
path = os.path.join(self.settings['static_path'], pagename)
self.render(pagename, hello="helo world")
def post(self, page):
pass

class OtherHandler(tornado.web.RequestHandler):
def get(self, page, extension):
pagename= page + '.' + extension
path = os.path.join(self.settings['static_path'], pagename)
print path
if extension != 'html':
with open(path) as f:
self.write(f.read())
pass

# 127.0.0.1/wx
class WxHandler(BaseHandler):
@tornado.web.asynchronous
def get(self):
logging.info('-------------- WxHandler GET ------------')
signature = self.get_argument("signature", None)
timestamp = self.get_argument("timestamp", None)
nonce = self.get_argument("nonce", None)
echostr = self.get_argument("echostr", None)

if not signature or not timestamp or not nonce or not echostr:
self.write('access weixin failed with params')
logging.warning("access weixin failed with params")
else:
if self.application.wxhelper.check_signature(signature, timestamp, nonce):
self.write(echostr)
logging.info("access weixin success")
else:
self.write('access weixin failed')
logging.warning("access weixin failed")

self.finish()

@tornado.web.asynchronous
def post(self):
logging.info('-------------- WxHandler POST ------------')
body = self.request.body
# logging.info(body)

xmlData = ET.fromstring(body)

msgType = xmlData.find('MsgType').text
toUser = xmlData.find('ToUserName').text
fromUser = xmlData.find('FromUserName').text
createTime = xmlData.find('CreateTime').text

if msgType == 'text':
msgId= xmlData.find("MsgId").text
content = xmlData.find('Content').text.encode("utf-8")
createTime = int(time.time())
textTpl = """<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
<MsgId>%s</MsgId>
</xml>"""
out = textTpl % (fromUser, toUser, createTime, msgType, content, msgId)
self.write(out)

elif msgType == 'event':
self.write('msg type is not support ' + msgType)
logging.warning("msg type is not support " + msgType)
else:
self.write('msg type is not support ' + msgType)
logging.warning("msg type is not support " + msgType)
self.finish()

# 授权登录
class WxAuthLoginHandler(BaseHandler):
@tornado.web.asynchronous
def get(self):
logging.info('-------------- WxHandler GET ------------')
CODE = self.get_argument('code', None)
# STATE = self.get_argument('state', None)
if CODE:
# 获取用户session
user_data = self.get_current_user()
if not user_data:
result = self.application.wxhelper.get_user_access_token(CODE)
if not result:
self.write(json.dumps({"errmsg":"request user access_token failed"}))
logging.error("request user access_token failed")
else:
over_time = int(time.time()) + result['expires_in']
user_data = {'openid':result["openid"],'access_token':result["access_token"], 'over_time':over_time}
# 写入cookie
self.set_current_user(user_data)

if user_data:
# 重定向到游戏
new_game_url = config.game_url + '?openid=' + user_data["openid"] + '&access_token='+user_data["access_token"]
new_game_url = config.game_url
self.redirect(new_game_url, permanent=True)
logging.info("WxAuthHandler redirect game url " + new_game_url)
# print '---- redirect game url ' + new_game_url
return
else:
self.write(json.dumps({"errmsg":"weixin auth failed with code is None"}))
logging.warning("weixin auth failed with code is None")

self.finish()



# http://xzdd.qianz.com/reqsign
class ReqWxSignHandler(BaseHandler):
@tornado.web.asynchronous
def get(self):
logging.info('-------------- ReqWxSignHandler GET ------------')
jsapi_ticket = self.application.wxhelper.get_jsapi_ticket()
url = config.game_url
ret = self.application.wxhelper.make_signature(jsapi_ticket, url)

data = json.dumps(ret)
logging.debug(data)
self.write(data)

#self.render('index.html')
self.finish()

@tornado.web.asynchronous
def post(self):
encrypt_key = self.get_argument('encrypt_key', None)
url = self.get_argument('url', None)
if encrypt_key and encrypt_key == config.encrypt_key and url:
logging.info('-------------- ReqWxSignHandler POST ------------')
jsapi_ticket = self.application.wxhelper.get_jsapi_ticket()
logging.info("req sign URL:" + url)
ret = self.application.wxhelper.make_signature(jsapi_ticket, url)
data = json.dumps(ret)
logging.info(data)
logging.info(jsapi_ticket)
self.write(data)
else:
self.write(json.dumps({"errmsg":"req sign post params invalid"}))
logging.warning("req sign post params invalid")

self.finish()


class WxShareHandler(BaseHandler):
@tornado.web.asynchronous
def get(self):
logging.info('-------------- WxShareHandler GET ------------')
jsapi_ticket = self.application.wxhelper.get_jsapi_ticket()
url = "http://xzdd.qianz.com/share"
url = "http://127.0.0.1/share"
ret = self.application.wxhelper.make_signature(jsapi_ticket, url)
self.render('share.html',appId = ret["appId"], timestamp = ret["timestamp"], nonceStr=ret["nonceStr"], signature = ret["signature"])
# self.finish()

# class ReqUserTokenHandler(BaseHandler):
# def get(self):
# # 获取用户session
# # self.set_default_headers()
# logging.info("ReqAccessTokenHandler")
# user_session = self.get_current_user()
# if not user_session:
# logging.warning("user_session is None")
# result = {"errcode":10001,"errmsg":"user session is None"}
# data = json.dumps(result)
# self.write(data)
# return

# # 认证
# ACCESS_TOKEN = None
# OPENDID = None
# auth_info = user_session.get_auth_info()
# if auth_info:
# data = {"access_token":ACCESS_TOKEN, "openid":OPENDID}
# data = json.dumps(result)
# self.write(data)
# else:
# result = {"errcode":10002,"errmsg":"user has not auth"}
# data = json.dumps(result)
# self.write(data)

# def post(self):
# self.set_default_headers()
# result = {"errcode":10002,"errmsg":"user has not auth"}
# data = json.dumps(result)
# self.write(data)


class RefreshWorker(threading.Thread):
def __init__(self, weixin_helper):
threading.Thread.__init__(self)
self.weixin_helper = weixin_helper

def run(self):
try:
while not self.weixin_helper.is_deleted:
while not self.weixin_helper.is_deleted and not self.weixin_helper.refresh_access_token():
time.sleep(300)

time.sleep(self.weixin_helper.expires_in - 100)
except Exception, e:
print Exception, ':', e


class CustomApplication(tornado.web.Application):
def __init__(self, debug=False):
handles = [
(r'/$', IndexHandler),
(r'/wx', WxHandler),
(r'/auth', WxAuthLoginHandler),
# (r'/reqtoken', ReqUserTokenHandler),
(r'/reqsign', ReqWxSignHandler),
(r'/share', WxShareHandler),
(r'/(.+?)\.html', OtherHtmlHandler),
(r'/(.+?)\.(.+)', OtherHandler),
]
settings = {
'static_path': os.path.join(os.path.dirname(__file__), 'templates'),
'template_path': os.path.join(os.path.dirname(__file__), 'templates'),
# 'login_url': '/login.html',
'cookie_secret': "61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o",
'xsrf_cookies': False,
'debug':debug
}
super(CustomApplication, self).__init__(handles, **settings)

def refresh_token(self):
logging.info('----------- timer refresh_token -----------')
self.wxhelper.refresh_access_token()
self.wxhelper.refresh_jsapi_ticket()

now_time = round(time.time())
for k, v in SessionMap.items():
if v['overtime'] < now_time:
print 'clean session', k
del SessionMap[k]
pass

def main():
tornado.options.parse_command_line()
# 实例化一个httpserver对象
application = CustomApplication(debug=options.debug)
application.wxhelper = WeixinHelper(config.appid, config.secret, config.token)

http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(options.port)

tornado.ioloop.IOLoop.instance().add_timeout(1, application.refresh_token) # 启动时执行一次
tornado.ioloop.PeriodicCallback(application.refresh_token,3600*1000).start() # 定期 2小时执行一次

loop = tornado.ioloop.IOLoop.instance()
tornado.autoreload.start(loop)
logging.info("web server start at port " + str(options.port))
loop.start()

if __name__ == '__main__':
main()



# taskkill /f /t /im python.exe

sd

项目

-gxgk-wechat-server

#

#

##

中国大学mooc

视频

视频