forked from ego008/gae-bbs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathyui.py
1860 lines (1478 loc) · 65.1 KB
/
yui.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
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
'''
@author: U{keakon<mailto:[email protected]>}
@license: the MIT License, see details in LICENSE.txt
@version: 1.1.2
'''
from __future__ import with_statement
from datetime import datetime, timedelta
# You can import sha1 or other hash algorithms instead of md5
# 你可以引入sha1等其他散列算法来代替md5
from hashlib import md5
import logging
import re
from threading import RLock
from time import time
from traceback import format_exc
from urlparse import urljoin, urlunsplit
from zlib import crc32
from google.appengine.api import users
try:
import webapp2 as webapp
except ImportError:
from google.appengine.ext import webapp
from webob.multidict import MultiDict
# HTTP status codes
# HTTP状态码
HTTP_STATUS = {
100: 'Continue',
101: 'Switching Protocols',
200: 'OK',
201: 'Created',
202: 'Accepted',
203: 'Non-Authoritative Information',
204: 'No Content',
205: 'Reset Content',
206: 'Partial Content',
300: 'Multiple Choices',
301: 'Moved Permanently',
302: 'Found',
303: 'See Other',
304: 'Not Modified',
305: 'Use Proxy',
307: 'Temporary Redirect',
400: 'Bad Request',
401: 'Unauthorized',
402: 'Payment Required',
403: 'Forbidden',
404: 'Not Found',
405: 'Method Not Allowed',
406: 'Not Acceptable',
407: 'Proxy Authentication Required',
408: 'Request Timeout',
409: 'Conflict',
410: 'Gone',
411: 'Length Required',
412: 'Precondition Failed',
413: 'Request Entity Too Large',
414: 'Request-URI Too Large',
415: 'Unsupported Media Type',
416: 'Requested Range Not Satisfiable',
417: 'Expectation Failed',
428: 'Precondition Required',
429: 'Too Many Requests',
500: 'Internal Server Error',
501: 'Not Implemented',
502: 'Bad Gateway',
503: 'Service Unavailable',
504: 'Gateway Timeout',
505: 'HTTP Version Not Supported',
511: 'Network Authentication Required'
}
class Property(object):
'''
Return a property attribute for new-style classes.
It only implement __get__ method, so you are free to set __dict__ to
override this property.
That's the only reason you would like to use it instead of the build-in
property function.
将方法封装成一个属性,适用于新风格的类。
由于只实现了__get__方法,所以你可以自由地设置__dict__,以覆盖对它的访问。
这也是你采用它,而不使用内建的property函数的唯一原因。
'''
def __init__(self, fget):
'''
@type fget: function
@param fget: the function for getting an attribute value
用于获取属性的函数
'''
self.fget = fget
self.__doc__ = fget.__doc__
def __get__(self, obj, objtype=None):
if obj is None:
return self
if self.fget is None:
raise AttributeError, 'unreadable attribute'
return self.fget(obj)
class CachedProperty(Property):
'''
Return a property attribute for new-style classes.
It works the same as Property, except caching the calculated property to its __dict__.
将方法封装成一个属性,适用于新风格的类。
作用与Property相同,不同之处是会把计算出来的属性缓存到__dict__。
'''
def __get__(self, obj, objtype=None):
if obj is None:
return self
fget = self.fget
if fget is None:
raise AttributeError, 'unreadable attribute'
obj.__dict__[fget.__name__] = prop = fget(obj)
return prop
class Request(webapp.Request):
'''
A simple request class with automatic Google Account authentication.
It's derived from webapp.Request, so you can use any methods and attributes
of webapp.Request.
可自动验证Google账号的请求类。
继承自webapp.Request,因此你可使用所有webapp.Request的方法和属性。
'''
__SPIDER_PATTERN = re.compile('(bot|crawl|spider|slurp|sohu-search|lycos|robozilla)', re.I)
@CachedProperty
def user(self):
'''
the current user of this request
发出请求的当前用户
'''
return users.get_current_user()
@CachedProperty
def login_logout_link(self):
if self.user:
return u'<a href="%s">退出</a>' % users.create_logout_url("/")
else:
return u'<a href="%s">Google帐户登录</a>' % users.create_login_url(self.uri)
@CachedProperty
def is_admin(self):
'''
whether the current user is admin
当前用户是否是管理员
'''
return users.is_current_user_admin()
@CachedProperty
def is_system(self):
'''
whether the current request is sent by Google App Engine system,
such as cron jobs, task queue, email handler and so on.
当前请求是否由Google App Engine系统发出,
例如计划任务、任务队列和邮件处理器等。
'''
return self.remote_addr[:2] == '0.'
@CachedProperty
def ua_details(self):
'''
parse browser, platform, os and vendor from user agent.
从user agent解析浏览器、平台、操作系统和产商信息。
@rtype: string
@return: tuple of browser, platform, os, os_version and vendor
browser, platform, os, os_version, vendor组成的元组
'''
user_agent = self.user_agent
os = ''
os_version = ''
browser = ''
platform = ''
vendor = ''
if user_agent:
if 'iPad' in user_agent:
os = 'iOS'
platform = 'iPad'
vendor = 'Apple'
elif 'iPod' in user_agent:
os = 'iOS'
platform = 'iPod Touch'
vendor = 'Apple'
elif 'iPhone' in user_agent:
os = 'iOS'
platform = 'iPhone'
vendor = 'Apple'
elif 'Android' in user_agent:
os = platform = 'Android'
elif 'BlackBerry' in user_agent:
os = 'BlackBerry OS'
platform = 'BlackBerry'
vendor = 'RIM'
elif 'Palm' in user_agent:
os = 'webOS'
platform = 'Palm'
elif 'Windows Phone' in user_agent:
os = 'Windows CE'
platform = 'Windows Phone'
elif 'PSP' in user_agent:
platform = 'PSP'
vendor = 'Sony'
elif 'Kindle' in user_agent:
os = 'Linux'
platform = 'Kindle'
elif 'Nintendo' in user_agent or 'Nitro' in user_agent:
platform = 'Wii'
vendor = 'Nintendo'
if not os:
if 'Windows' in user_agent:
os = 'Windows'
if 'Windows NT 6.1' in user_agent:
os_version = 'Windows 7'
elif 'Windows NT 5.1' in user_agent:
os_version = 'Windows XP'
elif 'Windows NT 6.0' in user_agent:
os_version = 'Windows Vista'
elif 'Windows NT 5.2' in user_agent:
os_version = 'Windows Server 2003'
elif 'Windows NT 5.0' in user_agent:
os_version = 'Windows 2000'
elif 'Windows CE' in user_agent:
os_version = 'Windows CE'
elif 'Macintosh' in user_agent or 'Mac OS' in user_agent:
os = 'Mac OS'
if 'Mac OS X' in user_agent:
os_version = 'Mac OS X'
elif 'Linux' in user_agent:
os = 'Linux'
elif 'FreeBSD' in user_agent:
os = 'FreeBSD'
elif 'OpenBSD' in user_agent:
os = 'OpenBSD'
elif 'Solaris' in user_agent:
os = 'Solaris'
elif 'Symbian' in user_agent or 'SymbOS' in user_agent:
os = 'SymbianOS'
self.is_mobile = True
if 'Series60' in user_agent or 'S60' in user_agent:
os_version = 'SymbianOS Series60'
elif 'Series40' in user_agent or 'S40' in user_agent:
os_version = 'SymbianOS Series40'
if not browser:
if 'MSIE' in user_agent:
browser = 'Internet Explorer'
elif 'Firefox' in user_agent:
browser = 'Firefox'
elif 'Chrome' in user_agent:
browser = 'Chrome'
elif 'Safari' in user_agent:
if 'Mobile' in user_agent:
browser = 'Mobile Safari'
self.is_mobile = True
else:
browser = 'Safari'
elif 'Opera Mini' in user_agent:
browser = 'Opera Mini'
self.is_mobile = True
elif 'Opera Mobi' in user_agent:
browser = 'Opera Mobile'
self.is_mobile = True
elif 'Opera' in user_agent:
browser = 'Opera'
elif 'UCWEB' in user_agent:
browser = 'UCWEB'
self.is_mobile = True
elif 'IEMobile' in user_agent:
browser = 'IEMobile'
self.is_mobile = True
if not vendor:
if 'Nokia' in user_agent:
vendor = 'Nokia'
elif 'motorola' in user_agent:
vendor = 'Motorola'
elif 'Sony' in user_agent:
vendor = 'Sony'
elif 'samsung' in user_agent.lower():
vendor = 'Samsung'
return browser, platform, os, os_version, vendor
@CachedProperty
def is_mobile(self):
'''
whether the request is send by a mobile user agent
发出请求的是否是手机浏览器
'''
environ = self.environ
if 'HTTP_X_WAP_PROFILE' in environ or 'HTTP_PROFILE' in environ or 'X-OperaMini-Features' in environ or\
self.first_match(('application/vnd.wap.xhtml+xml', 'text/vnd.wap.wml'), ''):
return True
user_agent = self.user_agent
if user_agent:
user_agent_lower = user_agent.lower()
if 'phone' in user_agent_lower or 'mobi' in user_agent_lower or 'wap' in user_agent_lower:
return True
browser, platform, os, os_version, vendor = self.ua_details
if platform or vendor:
return True
if 'is_mobile' in self.__dict__:
return self.__dict__['is_mobile']
return False
@CachedProperty
def is_spider(self):
'''
whether the current request is sent by a Search Engine spider.
当前请求是否由搜索引擎的蜘蛛发出。
'''
return self.__SPIDER_PATTERN.search(self.user_agent) is not None
@CachedProperty
def client_ip(self):
'''
the client's IP, return "Unknown" when can't find out
用户的IP
@rtype: string
@return: the client's IP or "Unknown" when can't find out
用户的IP,若找不到,则返回"unknown"
@note: The "HTTP_X_FORWARDED_FOR" variable may contain serveral IPs.
"HTTP_X_FORWARDED_FOR"变量可能包含多个IP。
'''
environ = self.environ
ip = environ.get('HTTP_X_REAL_IP', '') # if using nginx reverse proxy
if ip:
return ip
ip = environ.get('HTTP_CLIENT_IP', '')
if ip:
return ip
ip = environ.get('HTTP_X_FORWARDED_FOR', '')
if ip:
return ip
return environ.get('REMOTE_ADDR', 'unknown')
def first_match(self, mime_types, fallback='text/html'):
'''
Get the first match in the mime_types that is allowed.
获取mime_types中第一个允许的MIME类型。
@type mime_types: sequence
@param mime_types: a sequence for match
用于匹配的序列
@type fallback: string
@param fallback: the default MIME type if nothing is matched
当找不到匹配的类型时,返回该默认的MIME类型
@rtype: string
@return: the first match in the mime_types or
fallback if not matched
第一个匹配的MIME类型;若都不匹配,则返回fallback
'''
accept = self.accept.best_matches()
for mime_type in mime_types:
if mime_type in accept:
return mime_type
return fallback
class ResponseHeader(object):
'''
A mapping-like object which wraps response headers.
It's a litter faster than wsgiref.headers.Headers and
webob.headerdict.HeaderDict, because all the fields is treat as
single-valued except "Set-Cookie".
The disadvantage is you can't use it to handle multi-valued fields
like "Warning", but you almost won't use these fields.
一个类似于字典的,用于封装响应头的对象。
它比wsgiref.headers.Headers和webob.headerdict.HeaderDict稍快,
原因是除了"Set-Cookie",其他都当成单值来处理了。
缺点就是你无法用它处理多值字段,例如"Warning",但你几乎不会用到这些字段。
'''
def __init__(self, header=None, cookie=()):
'''
Initialize all header fields.
初始化所有的头字段。
@type header: dict
@param header: a dict object contains all header fields
包含所有头字段的字典对象
@type cookie: list
@param cookie: a list object contains all cookie fields
包含所有cookie的列表对象
'''
cookie = [('Set-Cookie', value) for value in cookie]
_header = {}
if header:
for name, value in header.iteritems():
if value is not None:
name = self._valid_name(name)
if name != 'Set-Cookie':
_header[name] = value
else:
cookie.append(('Set-Cookie', value))
self.__header = _header
self.__cookie = cookie
def __getitem__(self, name):
'''
Get the header field by name.
根据名称获取头字段。
@type name: string
@param name: the name of the header field (case-insensitive)
字段的名称(大小写不敏感)
@rtype: string
@return: the corresponding header field value of the name,
or None if hasn't been set
返回对应的头字段,如果未设置的话,则为None
@note: If you try to get "Set-Cookie" fields, it will return a list of
cookies' value or None. You'd better use L{get_cookies} method instead.
如果你使用这个方法来获取"Set-Cookie"字段,它将会返回所有cookie的值或None。
你最好是用L{get_cookies}方法来代替。
'''
name = self._valid_name(name)
if name != 'Set-Cookie':
return self.__header.get(name, None)
else:
return [cookie[1] for cookie in self.__cookie] or None
def __setitem__(self, name, value):
'''
Set the header field by name.
设置一个头字段。
@type name: string
@param name: the name of the header field (case-insensitive)
字段的名称(大小写不敏感)
@type value: string
@param value: the value of the header field,
if it's None, the field will be deleted
字段的名称,若为None,该字段将被删除
@note: There is a better way to add "Set-Cookie" fields: L{add_cookie}.
还有个更方便的L{add_cookie}方法可以添加"Set-Cookie"字段。
'''
name = self._valid_name(name)
if name != 'Set-Cookie':
if value is not None:
self.__header[name] = value
else:
self.__header.pop(name, None)
else:
if value is not None:
self.__cookie = [('Set-Cookie', value)]
else:
self.__cookie = []
def __delitem__(self, name):
'''
Delete a header field by name.
It won't raise a KeyError exception if the field is not exist.
根据名称来删除头字段。
如果字段不存在,不会引发KeyError异常。
@type name: string
@param name: the name of the header field (case-insensitive)
字段的名称(大小写不敏感)
'''
name = self._valid_name(name)
if name != 'Set-Cookie':
self.__header.pop(name, None)
else:
self.__cookie = []
def __contains__(self, name):
'''
Test whether a header field is exist.
@type name: string
@param name: the name of the header field (case-insensitive)
字段的名称(大小写不敏感)
@rtype: bool
@return: True if exist, otherwise False
返回对应的头字段,如果未设置的话,则为None
'''
name = self._valid_name(name)
if name != 'Set-Cookie':
return name in self.__header
else:
return self.__cookie != []
def setdefault(self, name, default_value):
'''
Set and return a header field if hasn't been set.
当头字段未被设置时,设置并返回它。
@type name: string
@param name: the name of the header field (case-insensitive)
字段的名称(大小写不敏感)
@type default_value: string
@param default_value: the default value should be returned if the field hasn't
been set
如果该字段未设置,则返回该默认值
@rtype: string or None
@return: the corresponding header field value of the name,
or default_value if hasn't been set
返回对应的头字段,如果未设置的话,则为default_value
@attention: Do B{not} use this method to set "Set-Cookie" fields,
you should use L{add_cookie} method instead.
B{请勿}使用这个方法设置"Set-Cookie"字段,你应该用L{add_cookie}方法来代替。
'''
name = self._valid_name(name)
if name != 'Set-Cookie':
if default_value is not None:
return self.__header.setdefault(name, default_value)
else:
return self.__header.get(name, None)
else:
if self.__cookie != []:
return [cookie[1] for cookie in self.__cookie]
elif default_value is not None:
self.__cookie = [('Set-Cookie', default_value)]
return [default_value]
else:
return None
def pop(self, name, default_value=None):
'''
Remove the header field by name and return it.
移除一个头字段,并返回它。
@type name: string
@param name: the name of the header field (case-insensitive)
字段的名称(大小写不敏感)
@type default_value: string
@param default_value: the default value should be returned if the field hasn't
been set
如果该字段未设置,则返回该默认值
@rtype: string
@return: the corresponding header field value of the name,
or default_value if hasn't been set
返回对应的头字段,如果未设置的话,则为default_value
'''
name = self._valid_name(name)
if name != 'Set-Cookie':
return self.__header.pop(name, default_value)
else:
if self.__cookie != []:
cookie = [cookie[1] for cookie in self.__cookie]
self.__cookie = []
return cookie
else:
return None
def add_cookie(self, name, value, expires=None, path=None, domain=None, secure=False, httponly=False):
'''
Add a "Set-Cookie" field.
添加一个"Set-Cookie"字段。
@type name: string
@param name: the name of the cookie
cookie的名称
@type value: string
@param value: the value of the cookie
cookie的值
@type expires: string, int or datetime
@param expires: the time the cookie expires,
if it's type is int, it will be set to current time plus expires seconds
cookie的有效期,如果类型为int,将被设为当前时间 + expires秒
@type domain: string
@param domain: the domain that the cookie is available
cookie的有效域
@type secure: bool
@param secure: indicates that the cookie should only be transmitted over
a secure HTTPS connection from the client
指明这个cookie只应该通过安全的HTTPS链接传送
@type httponly: bool
@param httponly: the cookie will be made accessible only through the
HTTP protocol if True, so the cookie won't be accessible by scripting
languages, such as JavaScript (not supported by all browsers)
如果为True,则只能通过HTTP协议来访问这个cookie,而不能通过其他的脚本,
例如JavaScript(并非所有浏览器都支持这个参数)
@note: This method is U{Netscape cookie specification
<http://devedge-temp.mozilla.org/library/manuals/2000/javascript/1.3/reference/cookies.html>}
compatible only, because IE 6 dosen't support U{RFC 2109
<http://www.ietf.org/rfc/rfc2109.txt>},
while Firefox 3.5 dosen't support U{RFC 2965
<http://www.ietf.org/rfc/rfc2965.txt>} either.
这个方法只兼容Netscape cookie草案,因为IE 6不支持RFC 2109,
而Firefox 3.5也不支持RFC 2965。
'''
cookie = ['%s=%s' % (name, value)]
if expires is not None:
if isinstance(expires, int):
cookie.append((datetime.utcnow() + timedelta(seconds=expires)).strftime('expires=%a, %d-%b-%Y %H:%M:%S GMT'))
elif isinstance(expires, datetime):
cookie.append(expires.strftime('expires=%a, %d-%b-%Y %H:%M:%S GMT'))
else:
cookie.append('expires=' + expires)
if path:
cookie.append('path=' + path)
if domain:
cookie.append('domain=' + domain)
if secure:
cookie.append('secure')
if httponly:
cookie.append('HttpOnly')
self.__cookie.append(('Set-Cookie', '; '.join(cookie)))
def get_cookies(self):
'''
Get all "Set-Cookie" fields.
获取所有的"Set-Cookie"字段。
@rtype: list
@return: a list of ('Set-Cookie', cookie content) tuples
由('Set-Cookie', cookie内容)组成的列表
'''
return self.__cookie[:]
def clear_cookies(self):
'''
Clear all "Set-Cookie" fields.
清除所有的"Set-Cookie"字段。
'''
self.__cookie = []
def items(self):
'''
Get all header fields.
获取所有的头字段。
@rtype: list
@return: a list of (field name, field value) tuples
由(字段名, 字段值)组成的列表
'''
return self.__header.items() + self.__cookie
def clear(self):
'''
Clear all the header fields.
清空所有头字段。
'''
self.__header = {}
self.__cookie = []
def __len__(self):
'''
Get the amount of all the header fields.
获得所有头字段的总数。
@rtype: int
@return: the amount of all the header fields
所有头字段的总数
'''
return len(self.__header) + len(self.__cookie)
@staticmethod
def _valid_name(name):
'''
Get the valid header field name.
获得有效的头字段名。
@type name: string
@param name: the name of the header field (case-insensitive)
字段的名称(大小写不敏感)
@rtype: string
@return: the valid header field name
有效的头字段名
'''
name = name.title()
if name == 'Etag':
return 'ETag'
if name == 'X-Xss-Protection':
return 'X-XSS-Protection'
if name == 'Www-Authenticate':
return 'WWW-Authenticate'
if name == 'Content-Md5':
return 'Content-MD5'
return name
def copy(self):
'''
@rtype: ResponseHeader
@return: a copy of this response header.
该响应的复本。
'''
header = ResponseHeader()
header.__header = self.__header.copy()
header.__cookie = self.__cookie[:]
return header
class Response(object):
'''
The response class which used to contain and handle the response content.
用于存储和处理响应内容的响应类。
'''
def __init__(self, start_response, status=200, header=None, body=''):
'''
@type start_response: function
@param start_response: the WSGI-compatible start_response function for
sending response
WSGI兼容的start_response函数,用于输出响应
@type status: int
@param status: the HTTP status code
HTTP状态码
@type header: ResponseHeader
@param header: the response header
响应头
@type body: str
@param body: the response body
响应体
'''
self._start_response = start_response
self.status = status
self.header = ResponseHeader() if header is None else header
if not body:
self.body = ''
elif isinstance(body, str):
self.body = body
elif isinstance(body, unicode):
self.body = body.encode('UTF-8')
else:
self.body = str(body)
def set_content_type(self, mime_type='text/html', charset='UTF-8'):
'''
Set the "Content-Type" header field.
设置"Content-Type"头字段。
@type mime_type: string
@param mime_type: the MIME type of output content,
these abbreviative notations are also available: xhtml, wap, wap2, json,
atom, rss.
输出内容的MIME类型,支持如下缩写:xhtml、wap、wap2、json、atom、rss。
@type charset: string
@param charset: the charset of output content
输出内容的字符集
'''
if mime_type != 'text/html':
if mime_type == 'xhtml':
mime_type = self.handler.request.first_match(('application/xhtml+xml',), 'text/html')
elif mime_type == 'wap':
mime_type = 'text/vnd.wap.wml'
elif mime_type == 'wap2':
mime_type = self.handler.request.first_match(('application/vnd.wap.xhtml+xml', 'application/xhtml+xml'), 'text/html')
elif mime_type == 'json':
mime_type = 'application/json'
elif mime_type == 'atom':
mime_type = 'application/atom+xml'
charset = ''
elif mime_type == 'rss':
mime_type = 'application/rss+xml'
charset = ''
self.header['Content-Type'] = '%s; charset=%s' % (mime_type, charset) if charset else mime_type
def set_cache(self, seconds, is_privacy=None):
'''
Set the user agent's cache strategy.
设置用户代理的缓存策略。
@type seconds: number
@param seconds: how many seconds should this response be cached
响应应被缓存多少秒
@type is_privacy: bool or None
@param is_privacy: whether the response can be stored in a shared
cache.
If it's None, it won't be cached by the edge cache of GAE;
if False, it won't be cached by shared caches of proxies;
if True, it can be cached by any cache.
响应是否能存储在一个共享缓存里.
若为None,将不会被GAE的边缘缓存所缓存;
若为False,将不会被代理服务器的共享缓存所缓存;
若为True,则可以被任何缓存所缓存。
'''
if seconds <= 0:
self.header['Cache-Control'] = self.header['Pragma'] = 'no-cache'
# fix localhost test for IE 6
# for performance reason, you can remove next line in production server
# 在本地开发服务器上用IE 6测试会出现bug
# 如果是在生产服务器上使用的话,可以去掉下面这行代码,减小header的体积
# 详情可见:http://www.keakon.cn/bbs/thread-1976-1-1.html
self.header['Expires'] = 'Fri, 01 Jan 1990 00:00:00 GMT'
else:
if is_privacy:
privacy = 'public, '
elif is_privacy is None:
privacy = ''
else:
privacy = 'private, '
self.header['Cache-Control'] = '%smax-age=%s' % (privacy, seconds)
def set_download_filename(self, filename):
'''
Set the file name to save the response content.
设置用于保存响应内容的文件名。
@type filename: str
@param filename: the file name to save.
用于保存的文件名。
'''
self.header['Content-Type'] = 'application/octet-stream'
self.header['Content-Disposition'] = 'attachment; filename=%s' % filename
def write(self, obj, encoding='utf-8'):
'''
Write an object to the output buffer.
将对象写入缓存。
@type obj: object
@param obj: the object which should be written to the buffer.
被写入缓存的对象。
@type encoding: str, unicode, or object
@param encoding: the unicode encoding.
unicode对象的编码。
@note: if the object type is not str or unicode, the str function will
be called to represent its value.
若对象类型不为str或unicode,会调用str函数来代表它的值。
'''
if isinstance(obj, str):
self.body += obj
elif isinstance(obj, unicode):
self.body += obj.encode(encoding)
else:
self.body += str(obj)
def get_status(self):
'''
Get HTTP status message from status code.
从HTTP状态码中获取状态信息。
@rtype: string
@return: the HTTP status message
HTTP状态信息
'''
return '%d %s' % (self.status, HTTP_STATUS[self.status])
def clear(self):
'''
Clear the output buffer.
清空输出缓存。
'''
self.body = ''
def send(self):
'''
Output the response content to the user agent.
You probably won't call it by yourself.
将响应内容输出给用户代理。
基本上你不需要手动去调用它。
'''
write = self._start_response(self.get_status(), self.header.items())
if self.body:
write(self.body)
def copy(self, copy_header=True, start_response=None):
'''
Return a copy of this response, which is mainly used for caching.
返回该响应的复本,主要用于缓存。
@type start_response: function
@param start_response: the start_response to be assigned to the copy.
复本的start_response属性。
@rtype: Response
@return: a copy of this response.
该响应的复本。
'''