├── examples ├── static │ └── main.css ├── templates │ └── graily_test.html ├── test_wsgiserver.py ├── test_httpserver.py ├── test_thread_poll_tcpserver.py ├── test_tcpserver.py ├── test_graily_tornadowsgi.py └── test_graily.py ├── .gitignore ├── README.md ├── LICENSE └── graily.py /examples/static/main.css: -------------------------------------------------------------------------------- 1 | h2 { 2 | font-size:13px; 3 | color: red; 4 | } 5 | -------------------------------------------------------------------------------- /examples/templates/graily_test.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 |

你好, {{ name }}

7 | 8 | {{ "
  • %s: %s
  • " % (i, parameters[i]) for i in parameters }} 9 | 10 | 11 | -------------------------------------------------------------------------------- /examples/test_wsgiserver.py: -------------------------------------------------------------------------------- 1 | from graily import make_server, init_log 2 | from bottle import route, default_app 3 | import logging 4 | 5 | @route("/") 6 | def test(): 7 | return "hello from bottle with Graily" 8 | 9 | def main(): 10 | init_log(level=logging.DEBUG) 11 | app = default_app() 12 | server = make_server(("", 8888), app) 13 | server.serve_forever() 14 | 15 | if __name__ == '__main__': 16 | main() 17 | -------------------------------------------------------------------------------- /examples/test_httpserver.py: -------------------------------------------------------------------------------- 1 | from graily import HTTPServer, BaseHTTPRequestHandler, init_log 2 | 3 | def main(): 4 | import logging 5 | init_log(level=logging.DEBUG) 6 | 7 | class Test(BaseHTTPRequestHandler): 8 | def GET(self): 9 | return "hello from graily httpserver" 10 | def POST(self): 11 | return str(self.parameters) 12 | 13 | server = HTTPServer(("", 8888), Test) 14 | server.serve_forever() 15 | 16 | if __name__ == '__main__': 17 | main() 18 | -------------------------------------------------------------------------------- /examples/test_thread_poll_tcpserver.py: -------------------------------------------------------------------------------- 1 | import time 2 | from graily import ThreadPollTCPServer, Concurrent, StreamRequestHandler, init_log 3 | 4 | def main(): 5 | import logging 6 | init_log(level=logging.DEBUG) 7 | 8 | class Echo(StreamRequestHandler): 9 | @Concurrent.register 10 | def dataReceived(self): 11 | time.sleep(5) # won't block the main Thread 12 | self.write(self.data) 13 | server = ThreadPollTCPServer(("", 8888), Echo) 14 | server.serve_forever() 15 | 16 | if __name__ == '__main__': 17 | main() 18 | -------------------------------------------------------------------------------- /examples/test_tcpserver.py: -------------------------------------------------------------------------------- 1 | from graily import TCPServer, StreamRequestHandler, init_log 2 | 3 | def main(): 4 | import logging 5 | init_log(level=logging.DEBUG) 6 | 7 | class Echo(StreamRequestHandler): 8 | def verify_request(self): 9 | # Request finished when received data ends with '.', 10 | # you can also define your own protocol 11 | return bytes([self.iostream._read_buffer[-1]]) == b'.' 12 | 13 | def dataReceived(self): 14 | self.write(self.data) 15 | 16 | server = TCPServer(("", 8888), Echo) 17 | server.serve_forever() 18 | 19 | if __name__ == '__main__': 20 | main() 21 | -------------------------------------------------------------------------------- /examples/test_graily_tornadowsgi.py: -------------------------------------------------------------------------------- 1 | from graily import Graily, HTTPResponse, template, StaticFileHandler, Concurrent, init_log 2 | import tornado 3 | from tornado import wsgi, httpserver 4 | 5 | def main(): 6 | import logging 7 | init_log(level=logging.DEBUG) 8 | 9 | class Test(HTTPResponse): 10 | def get(self): 11 | return "hello from Graily and tornado WSGIServer" 12 | 13 | app = Graily([(r'^.*$', Test)]) 14 | container = wsgi.WSGIContainer(app) 15 | http_server = httpserver.HTTPServer(container) 16 | http_server.listen(8888) 17 | tornado.ioloop.IOLoop.instance().start() 18 | 19 | if __name__ == '__main__': 20 | main() 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | *.egg-info/ 23 | .installed.cfg 24 | *.egg 25 | 26 | # PyInstaller 27 | # Usually these files are written by a python script from a template 28 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 29 | *.manifest 30 | *.spec 31 | 32 | # Installer logs 33 | pip-log.txt 34 | pip-delete-this-directory.txt 35 | 36 | # Unit test / coverage reports 37 | htmlcov/ 38 | .tox/ 39 | .coverage 40 | .coverage.* 41 | .cache 42 | nosetests.xml 43 | coverage.xml 44 | *,cover 45 | 46 | # Translations 47 | *.mo 48 | *.pot 49 | 50 | # Django stuff: 51 | *.log 52 | 53 | # Sphinx documentation 54 | docs/_build/ 55 | 56 | # PyBuilder 57 | target/ 58 | -------------------------------------------------------------------------------- /examples/test_graily.py: -------------------------------------------------------------------------------- 1 | from graily import Graily, HTTPResponse, template, StaticFileHandler, Concurrent, init_log 2 | import time 3 | 4 | def main(): 5 | import logging 6 | init_log(level=logging.DEBUG) 7 | 8 | class Temp(HTTPResponse): 9 | def get(self): 10 | return template("graily_test.html", 11 | {'parameters': self.parameters, 'name': 'Graily'}) 12 | 13 | class Test(HTTPResponse): 14 | def get(self, name): 15 | return "hello, {}".format(name) 16 | 17 | def post(self, name): 18 | return template("graily_test.html", 19 | parameters=self.parameters, name=name) 20 | 21 | class ConTest(HTTPResponse): 22 | @Concurrent.register 23 | def get(self): 24 | time.sleep(5) # won't block the main Thread 25 | return "hello from Graily concurrent" 26 | 27 | app = Graily([ 28 | (r'^/temp/$', Temp), 29 | (r'^/static/(.*)$', StaticFileHandler.set_path("static")), 30 | (r'^/con/$', ConTest), 31 | (r'^/(.*)/$', Test), 32 | ]) 33 | app.server_bind(("", 8888)) 34 | app.serve_forever() 35 | 36 | if __name__ == '__main__': 37 | main() 38 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Graily Web Server 2 | Graily is a no-blocking web server and micro web-framework written by Python. It's only support for Python3 and Linux platform. 3 | 4 | * **Lightweight And Fast :** It's has no dependencies other than the standard library. And it's fast. 5 | * **Long-Polling :** Graily can handle tens of thousands of connections for long polling. 6 | * **WSGI Server Support :** Graily has support for WSGI, so it can be used as a HTTP server for any other frameworks. 7 | * **Concurrent :** Graily can chose to use Concurrent class to handle those request which may blocking the main thread. 8 | 9 | #####Here is a sample "Hello, world" example: 10 | ```python 11 | from graily import Graily, HTTPResponse 12 | 13 | class MainHandler(HTTPResponse): 14 | def get(self): 15 | return "Hello, world" 16 | 17 | server = Graily([ 18 | (r'^/$', MainHandler), 19 | ]) 20 | server.server_bind(("", 8888)) 21 | server.serve_forever() 22 | ``` 23 | #####Concurrent example: 24 | ```python 25 | from graily import Graily, HTTPResponse, Concurrent 26 | import time 27 | 28 | class MainHandler(HTTPResponse): 29 | @Concurrent.register 30 | def get(self): 31 | time.sleep(5) # won't blocking the main Thread 32 | return "Hello, world" 33 | 34 | server = Graily([ 35 | (r'^/$', MainHandler), 36 | ]) 37 | server.server_bind(("", 8888)) 38 | server.serve_forever() 39 | ``` 40 | #####WSGI server with Bottle Application example: 41 | ```python 42 | from bottle import route, default_app 43 | from graily import make_server 44 | 45 | @route('/') 46 | def main(): 47 | return 'hello from bottle.' 48 | 49 | application = default_app() 50 | server = make_server(('', 8888), application) 51 | server.serve_forever() 52 | ``` 53 | You can find more examples (concurrent, template) in [examples](https://github.com/lazywen/graily/tree/master/examples). -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /graily.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | __all__ = [ 5 | # tcp server 6 | 'TCPServer', 'ThreadPollTCPServer', 'StreamRequestHandler', 7 | # http server 8 | 'HTTPServer', 'ThreadPollHTTPServer', 'BaseHTTPRequestHandler', 9 | 'HTTPResponse', 'StaticFileHandler' 10 | # wsgi server 11 | 'WSGIServer', 'WSGIRequestHandler', 'make_server', 12 | # templates 13 | 'BaseTemplate', 'templates', 'MakoTemplate', 14 | # main application and others 15 | 'Graily', 'Concurrent', 'init_log' 16 | ] 17 | 18 | import os, sys, re, errno, time, socket, select, logging, random, types, io 19 | import mimetypes, functools, heapq 20 | import traceback 21 | assert sys.version_info>=(3,0,0), "Only support for Python3" 22 | 23 | import queue 24 | import _thread, threading 25 | 26 | from select import epoll 27 | from urllib.parse import urlparse, parse_qs 28 | 29 | class GrailyPoll: 30 | '''main Poll loop''' 31 | 32 | READ = select.EPOLLIN 33 | WRITE = select.EPOLLOUT 34 | ERROR = select.EPOLLERR | select.EPOLLHUP 35 | MAX_KEEPALIVE_TIME = 300 36 | 37 | server_name = "Graily" 38 | 39 | def __init__(self, server_address, RequestHandler, allow_reuse_address=True, 40 | max_input_size=2097152): 41 | self.server_address = server_address 42 | self.RequestHandler = RequestHandler 43 | self.allow_reuse_address = allow_reuse_address 44 | self.max_input_size = max_input_size 45 | self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 46 | self._sockets = {self.socket.fileno(): self.socket} 47 | self._shutdown_request = True 48 | self._handlers = {} 49 | self._keepalive = {} 50 | 51 | self.server_bind() 52 | 53 | def init_socket(self): 54 | logging.info('Starting server at {}'.format(self.server_address)) 55 | if self.allow_reuse_address: 56 | self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 57 | self.socket.bind(self.server_address) 58 | self.server_address = self.socket.getsockname() 59 | self.socket.setblocking(False) 60 | self.socket.listen(100) 61 | self.init_epoll() 62 | 63 | def init_epoll(self): 64 | self.epoll = epoll() 65 | self.epoll.register(self.socket, self.READ | self.ERROR) 66 | 67 | def server_bind(self): 68 | self.init_socket() 69 | self.init_epoll() 70 | 71 | def server_close(self): 72 | self.socket.close() 73 | 74 | def shutdown_request(self, request, flag=socket.SHUT_WR): 75 | try: request.shutdown(flag) 76 | except OSError: pass 77 | 78 | def close_request(self, request): 79 | try: request.close() 80 | except OSError: pass 81 | 82 | def _run(self, timeout=1): 83 | # TODO timeout 84 | 85 | try: 86 | event_pairs = self.epoll.poll(timeout) 87 | # logging.debug("event: {}".format(event_pairs)) 88 | # logging.debug("sockets: {}".format([i for i in self._sockets])) 89 | # logging.debug("handlers: {}".format([(i.fileno(), self._handlers[i]) for i in self._handlers ])) 90 | except Exception as e: 91 | if errno_from_exception(e) == errno.EINTR: 92 | return 93 | else: raise 94 | 95 | for fd, event in event_pairs: 96 | sock = self._sockets[fd] 97 | if event & self.ERROR: 98 | self.epoll.unregister(fd) 99 | del self._sockets[fd] 100 | self._handlers.pop(sock, None) 101 | self._keepalive.pop(sock, None) 102 | self.close_request(sock) 103 | else: 104 | try: 105 | if sock is self.socket: 106 | if not self._shutdown_request: 107 | request, client_address = sock.accept() 108 | request.setblocking(False) 109 | _fd = request.fileno() 110 | self._sockets[_fd] = request 111 | self.epoll.register(request, self.READ | self.ERROR) 112 | self._keepalive[request] = time.time() 113 | # TODO wait threads exit 114 | else: time.sleep(timeout) 115 | 116 | elif event & self.READ: 117 | self._keepalive[sock] = time.time() 118 | self.handle_request(sock) 119 | elif event & self.WRITE: 120 | self.handle_response(sock) 121 | 122 | except (OSError, IOError) as e: 123 | if errno_from_exception(e) == errno.EPIPE: 124 | # Happens when the client closes the connection 125 | pass 126 | except Exception as e: 127 | self.handle_exception(e, sock) 128 | 129 | # do something when no events 130 | if len(event_pairs) == 0: 131 | for _fd, _sock in self._sockets.items(): 132 | if _sock not in self._keepalive: 133 | self._keepalive[_sock] = time.time() 134 | for _sock, _time in self._keepalive.items(): 135 | if time.time()-_time >= self.MAX_KEEPALIVE_TIME: 136 | self.shutdown_request(_sock) 137 | 138 | def handle_exception(self, err, sock): 139 | logging.exception('') 140 | if sock is self.socket: time.sleep(1) 141 | else: self.shutdown_request(sock) 142 | 143 | def handle_request(self, sock): 144 | if sock not in self._handlers: 145 | self._handlers[sock] = self.RequestHandler(sock, self) 146 | self._handlers[sock]._run() 147 | 148 | def handle_response(self, sock): 149 | handler = self._handlers[sock] 150 | sent = sock.send(handler.iostream._write_buffer) 151 | # logging.debug('epoll sent: %s' % sent) 152 | if sent >= len(handler.iostream._write_buffer): 153 | self.update_handler(sock, self.READ) 154 | handler.iostream._write_buffer = handler.iostream._write_buffer[sent:] 155 | 156 | def update_handler(self, sock, event): 157 | self.epoll.modify(sock, event | self.ERROR) 158 | 159 | 160 | class TCPServer(GrailyPoll): 161 | '''tcp server''' 162 | def __init__(self, server_address, RequestHandler, **kwargs): 163 | super(TCPServer, self).__init__(server_address, RequestHandler, 164 | **kwargs) 165 | 166 | def serve_forever(self): 167 | self._shutdown_request = False 168 | while not self._shutdown_request or len(self.sockets)>1: 169 | self._run() 170 | 171 | class ThreadPollTCPServer(TCPServer): 172 | '''use threading poll for handler''' 173 | def __init__(self, server_address, RequestHandler, 174 | poll_size=100, max_tasks=1000, **kwargs): 175 | super(ThreadPollTCPServer, self).__init__(server_address, RequestHandler, **kwargs) 176 | if Concurrent._concurrency: 177 | self.concurrent = Concurrent(poll_size, max_tasks, self) 178 | 179 | def put_task(self, task): 180 | self.concurrent.tasks.put(task) 181 | 182 | def serve_forever(self): 183 | if Concurrent._concurrency: self.concurrent.start() 184 | self._shutdown_request = False 185 | while not self._shutdown_request or len(self.sockets)>1: 186 | self._run() 187 | 188 | class HTTPServer(TCPServer): 189 | '''HTTP server''' 190 | 191 | class ThreadPollHTTPServer(ThreadPollTCPServer): 192 | '''HTTPServer use threading poll for handler''' 193 | 194 | class WSGIServer(HTTPServer): 195 | application = None 196 | def server_bind(self): 197 | """Override server_bind to store the server name.""" 198 | HTTPServer.server_bind(self) 199 | self.setup_environ() 200 | 201 | def setup_environ(self): 202 | # Set up base environment 203 | env = self.base_environ = {} 204 | env['SERVER_NAME'] = self.server_name 205 | env['GATEWAY_INTERFACE'] = 'CGI/1.1' 206 | env['SERVER_PORT'] = str(self.server_address[1]) 207 | env['REMOTE_HOST']='' 208 | env['CONTENT_LENGTH']='' 209 | env['SCRIPT_NAME'] = '' 210 | 211 | def get_app(self): 212 | return self.application 213 | 214 | def set_app(self,application): 215 | self.application = application 216 | 217 | class Concurrent: 218 | # when _concurrency is True, the server will start thread poll 219 | _concurrency = False 220 | 221 | def __init__(self, poll_size, max_tasks, server): 222 | self.poll_size = poll_size 223 | self.tasks = queue.Queue(max_tasks) 224 | self.server = server 225 | self._thread_poll = [] 226 | self._running = False 227 | 228 | def start(self): 229 | logging.info('starting thread poll ...') 230 | if self._running: 231 | logging.warning('thread poll already started!') 232 | return 233 | 234 | def worker(): 235 | while True: 236 | task = self.tasks.get() 237 | # logging.debug(threading.current_thread().getName()+' got a task: '+str(task)) 238 | # time.sleep(random.randint(1,5)/10) 239 | 240 | next(task['run']) 241 | try: res = task['run'].send(task['args']) 242 | except StopIteration: pass 243 | except Exception as e: 244 | self.server.handle_exception(e, task['socket']) 245 | else: 246 | if res and 'result_handler' in task: 247 | task['result_handler'](res) 248 | if 'callback' in task and len(task['callback'])>0: 249 | for callback, args in task['callback']: 250 | callback(*args) 251 | 252 | for i in range(self.poll_size): 253 | td = threading.Thread(target=worker, args=()) 254 | td.setDaemon(True) 255 | td.start() 256 | self._thread_poll.append(td) 257 | self._running = True 258 | 259 | def allocate(self): 260 | # TODO 261 | pass 262 | 263 | class register: 264 | ''' 265 | the register decorator can make the method concurrent: 266 | 267 | @Concurrent.register 268 | def get(self): 269 | self.write("hello, world") 270 | 271 | ''' 272 | 273 | def __init__(self, func): 274 | self.func = func 275 | self.__dict__['_graily_concurrency'] = True 276 | if not Concurrent._concurrency: 277 | Concurrent._concurrency = True 278 | def __call__(self, *args, **kwargs): 279 | ora_args = yield 280 | new_args = [] 281 | if ora_args: new_args.extend(ora_args) 282 | new_args.extend(args) 283 | yield self.func(*new_args, **kwargs) 284 | 285 | class BaseRequestHandler: 286 | ''' 287 | The base request handler class, you must implemente those method: 288 | 289 | parse_request 290 | verify_request 291 | dataReceived 292 | ''' 293 | 294 | def __init__(self, request, server): 295 | self.request = request 296 | self.server = server 297 | self.iostream = BaseIOStream(request, server) 298 | self.response_handler = self.dataReceived 299 | self._initialize() 300 | 301 | def _initialize(self): 302 | pass 303 | 304 | def write(self, res): 305 | if not self.iostream.write(res): 306 | self.server.update_handler(self.request, self.server.WRITE) 307 | 308 | def close(self): 309 | self.server.shutdown_request(self.request) 310 | 311 | def _run(self): 312 | data_ready = self.iostream.read() 313 | if data_ready and self.verify_request(): 314 | if self.parse_request(): 315 | prg = self.dataReceived() 316 | if isinstance(prg, types.GeneratorType) and '_graily_concurrency' \ 317 | in self.dataReceived.__dict__: 318 | task = {'socket': self.request, 'run': prg, 'args':(self,), 319 | 'callback': [(self._initialize, ())]} 320 | self.server.put_task(task) 321 | else: self._initialize() 322 | 323 | 324 | def parse_request(self): 325 | '''pop data that you need from iostream._read_buffer and keep the 326 | others. 327 | ''' 328 | raise NotImplementedError 329 | 330 | def verify_request(self): 331 | ''' verify the received data with your own protocol, return True 332 | if the data is correct and a False value if not correct. 333 | ''' 334 | raise NotImplementedError 335 | 336 | def dataReceived(self): 337 | raise NotImplementedError 338 | 339 | class StreamRequestHandler(BaseRequestHandler): 340 | ''' The request handler for TCPServer ''' 341 | def _initialize(self): 342 | pass 343 | 344 | def parse_request(self): 345 | self.data = self.iostream._read_buffer.decode() 346 | self.iostream._read_buffer = b"" 347 | return True 348 | 349 | def verify_request(self): 350 | return bool(self.iostream._read_buffer) 351 | 352 | class BaseHTTPRequestHandler(BaseRequestHandler): 353 | ''' The request hansler for HTTPServer ''' 354 | 355 | SUPPORT_HTTP_VERSION = ('HTTP/1.0', 'HTTP/1.1') 356 | HTTP_METHOD = ('HEAD', 'GET', 'POST', 'OPTIONS', 'PUT', 'DELETE', 'TRACE', 'CONNECT') 357 | ERROR_MESSAGE_TEMPLATE = ('' 358 | '%(code)d %(msg)s' 359 | '

    %(code)d %(msg)s

    ' 360 | '

    %(desc)s

    ' 361 | '' 362 | '') 363 | DEBUG_MESSAGE_TEMPLATE = () 364 | 365 | def _initialize(self): 366 | self._send_buffer = b"" 367 | self.keep_alive = False 368 | self.command = "" 369 | self.host = "" 370 | self.parameters = {} 371 | self.request_url = "" 372 | self.request_head = None 373 | self.request_body = None 374 | self.request_path = "" 375 | self.request_query = "" 376 | self.http_version = "" 377 | self.headers = {} 378 | self.respond_status = 200 379 | self.request_options = {} 380 | self.header_sent = False 381 | self.environ = {'write':self.write, 'send_error':self.send_error, 382 | 'set_header':self.set_header, 'set_response_status':self.set_response_status} 383 | 384 | def verify_request(self): 385 | # return b'HTTP/1.' in self.iostream._read_buffer and \ 386 | # b'\r\n\r\n' in self.iostream._read_buffer 387 | return b'\r\n\r\n' in self.iostream._read_buffer 388 | 389 | def parse_request(self): 390 | self.data = self.iostream._read_buffer.decode() 391 | self.iostream._read_buffer = b"" 392 | slices = self.data.split('\r\n\r\n') 393 | if len(slices) > 2: 394 | self.send_error(400) 395 | return False 396 | self.environ['request_head'] = self.request_head = slices[0] 397 | self.environ['request_body'] = self.request_body = slices[1] 398 | 399 | request_head = io.StringIO(self.request_head) 400 | request_line = request_head.readline().rstrip('\r\n') 401 | args = request_line.split() 402 | if len(args) == 3: 403 | self.command = args[0] 404 | self.request_url = args[1] 405 | self.http_version = args[2] 406 | 407 | _urlpar = urlparse(self.request_url) 408 | self.environ['request_path'] = self.request_path = _urlpar.path 409 | self.environ['request_query'] = self.request_query = _urlpar.query 410 | 411 | if self.http_version not in self.SUPPORT_HTTP_VERSION: 412 | self.send_error(505, "HTTP Version {} Not Supported".format(self.http_version)) 413 | return False 414 | if self.command not in self.HTTP_METHOD: 415 | self.send_error(405, "Not Allowed: {}".format(self.command)) 416 | return False 417 | 418 | while True: 419 | line = request_head.readline() 420 | if not line: break 421 | pos = line.find(':') 422 | if pos < 0: 423 | self.send_error(400); return False 424 | self.request_options[line[0:pos].strip()] = line[pos+1:].strip() 425 | 426 | if 'Host' not in self.request_options: 427 | self.send_error(400); return False 428 | if self.request_options.get('Connection', '').lower() == 'keep-alive': 429 | self.keep_alive = True 430 | 431 | if self.command == 'GET': 432 | self.parameters = parse_qs(self.request_query) 433 | elif self.command == 'POST': 434 | self.parameters = parse_qs(self.request_body) 435 | if self.parameters: 436 | for key, val in self.parameters.items(): 437 | if type(val)==list and len(val)==1: 438 | self.parameters[key] = val[0] 439 | self.environ['parameters'] = self.parameters 440 | return True 441 | 442 | elif len(args) == 2: 443 | # HTTP/0.9 444 | self.send_error(400, 'not support') 445 | else: self.send_error(400, "bad request syntax") 446 | return False 447 | 448 | def set_response_status(self, code): 449 | assert type(code) == int 450 | self.respond_status = code 451 | def set_header(self, opt, val): 452 | self.headers[opt] = val 453 | 454 | def send_response(self, body=None): 455 | if not self.header_sent: 456 | self._send_buffer = ("{} {} {}\r\n".format(self.http_version, self.respond_status, \ 457 | self.RESPONSES_CODE.get(self.respond_status, '???'))).encode('latin-1', 'strict') 458 | self.respond_status = 200 459 | for opt, val in self.headers.items(): 460 | self._send_buffer += ("{}: {}\r\n".format(opt, val)).encode('latin-1', 'strict') 461 | self._send_buffer += b'\r\n' 462 | self.headers = {} 463 | self.header_sent = True 464 | _data = self._send_buffer 465 | if type(body)==str: 466 | body = body.encode('utf-8', 'replace') 467 | if body: _data += body 468 | self._write(_data) 469 | self._send_buffer = b"" 470 | 471 | def send_error(self, code, desc=""): 472 | msg = self.RESPONSES_CODE.get(code) 473 | body = (self.ERROR_MESSAGE_TEMPLATE % {'code':code, 'msg':msg, 'desc': desc}) 474 | self.set_response_status(code) 475 | self.set_header("Content-Type", "text/html; charset=UTF-8") 476 | self.set_header('Connection', 'close') 477 | self.set_header('Content-Length', int(len(body))) 478 | self.send_response(body) 479 | # TODO 480 | self.server.shutdown_request(self.request) 481 | 482 | def _write(self, res): 483 | if not self.iostream.write(res): 484 | self.server.update_handler(self.request, self.server.WRITE) 485 | 486 | def write(self, data, finish=False): 487 | '''support HTTP long polling''' 488 | # assert type(data) == str 489 | self.set_header('Connection', 'keep-alive') 490 | if finish and "Content-Length" not in self.headers: 491 | try: data_length = len(data) 492 | except: pass 493 | else: self.set_header('Content-Length', str(data_length)) 494 | if "Content-Type" not in self.headers: 495 | self.set_header("Content-Type", "text/html; charset=UTF-8") 496 | if type(data) == types.GeneratorType: 497 | headers_sent = False 498 | for _d in data: 499 | if type(_d)==str: _d=_d.encode('utf-8','replace') 500 | if not headers_sent: 501 | self.send_response() 502 | headers_sent = True 503 | if _d: self._write(_d) 504 | else: 505 | self.send_response(data) 506 | 507 | def _run(self): 508 | data_ready = self.iostream.read() 509 | if data_ready and self.verify_request(): 510 | if self.parse_request(): 511 | self.dataReceived() 512 | 513 | def dataReceived(self): 514 | _concurrency = False 515 | if self.command == 'HEAD': 516 | self.write('') 517 | elif self.command in ('GET', 'POST'): 518 | if hasattr(self, 'get_handler'): 519 | handler, args = self.get_handler(self.request_path) 520 | ins = handler(self.environ) 521 | if hasattr(ins, self.command.lower()): 522 | func = getattr(ins, self.command.lower()) 523 | res = func(*args) 524 | if type(res) == types.GeneratorType and '_graily_concurrency' \ 525 | in func.__dict__: 526 | _concurrency = True 527 | task = {'socket': self.request, 'run': res, 'args':(self,), 528 | 'callback': [(self._initialize, ())], 529 | 'result_handler':functools.partial(self.write, finish=True)} 530 | self.server.put_task(task) 531 | else: 532 | if res: self.write(res, finish=True) 533 | else: self.send_error(501, "{} Method Not Implemented".format(self.command)) 534 | else: 535 | if hasattr(self, self.command): 536 | res = getattr(self, self.command)() 537 | if res: self.write(res, finish=True) 538 | else: self.send_error(501, "{} Method Not Implemented".format(self.command)) 539 | 540 | if not _concurrency: 541 | if not self.keep_alive: 542 | self.server.shutdown_request(self.request) 543 | self._initialize() 544 | 545 | RESPONSES_CODE = { 546 | 100: 'Continue', 101: 'Switching Protocols', 547 | 548 | 200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non-Authoritative Information', 549 | 204: 'No Content', 205: 'Reset Content', 206: 'Partial Content', 550 | 551 | 300: 'Multiple Choices', 301: 'Moved Permanently', 302: 'Found', 303: 'See Other', 552 | 304: 'Not Modified', 305: 'Use Proxy', 307: 'Temporary Redirect', 553 | 554 | 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 555 | 404: 'Not Found', 405: 'Method Not Allowed', 406: 'Not Acceptable', 556 | 407: 'Proxy Authentication Required', 408: 'Request Timeout', 409: 'Conflict', 557 | 410: 'Gone', 411: 'Length Required', 412: 'Precondition Failed', 558 | 413: 'Request Entity Too Large', 414: 'Request-URI Too Long', 415: 'Unsupported Media Type', 559 | 416: 'Requested Range Not Satisfiable', 417: 'Expectation Failed', 428: 'Precondition Required', 560 | 429: 'Too Many Requests', 431: 'Request Header Fields Too Large', 561 | 562 | 500: 'Internal Server Error', 501: 'Not Implemented', 502: 'Bad Gateway', 563 | 503: 'Service Unavailable', 504: 'Gateway Timeout', 505: 'HTTP Version Not Supported', 564 | 511: 'Network Authentication Required', 565 | } 566 | 567 | class HTTPResponse: 568 | ''' 569 | HTTPResponse is use for handle HTTP method: 570 | 571 | class MainHanlder(HTTPResponse): 572 | def get(self): 573 | self.write("hello, world") 574 | ''' 575 | 576 | def __init__(self, environ): 577 | self.base_environ = environ.copy() 578 | self.headers = {} 579 | self.init_environ() 580 | def init_environ(self): 581 | for k,v in self.base_environ.items(): 582 | setattr(self, k ,v) 583 | 584 | class NotFoundHandler(HTTPResponse): 585 | code = 404 586 | def get(self, *args): 587 | return self.send_error(404, "not found for: {}".format(self.request_path)) 588 | def post(self, *args): 589 | return self.get(*args) 590 | 591 | class StaticFileHandler(HTTPResponse): 592 | static_path = None 593 | def get(self, rel_path): 594 | if not self.static_path: 595 | raise ValueError("static_path not set!") 596 | if rel_path.endswith('/'): 597 | return self.send_error(403, "Your Request Is Forbidden: {}".format(rel_path)) 598 | path = os.path.join(self.static_path, rel_path) 599 | if os.path.isfile(path): 600 | self.set_response_status(200) 601 | extension = os.path.splitext(path)[1].lower() 602 | ctype = self.extensions_map.get(extension, self.extensions_map['']) 603 | self.set_header("Content-Type", ctype) 604 | # not allowed hop-by hop 605 | # self.set_header("Connection", "close") 606 | f = open(path, 'rb') 607 | fs = os.fstat(f.fileno()) 608 | self.set_header("Content-Length", str(fs[6])) 609 | 610 | # TODO Last-Modified, and return 302 if not modified 611 | # self.set_header("Last-Modified", self.format_time(fs.st_mtime)) 612 | 613 | # read all contents to memory when request a small file 614 | if fs[6] < 102400: return f.read() 615 | else: return self.yield_file(f) 616 | else: return self.send_error(404, "Not Found: {}".format(rel_path)) 617 | 618 | def yield_file(self, fd): 619 | chunk_size = 61440 # <65535 620 | _c = fd.read(chunk_size) 621 | while _c: 622 | yield _c 623 | _c = fd.read(chunk_size) 624 | 625 | @classmethod 626 | def set_path(cls, path): 627 | full_path = os.path.join(os.path.dirname( 628 | os.path.abspath(__file__)), path) 629 | if os.path.isdir(full_path): 630 | StaticFileHandler.static_path = full_path 631 | else: raise ValueError("no such path: {}".format(full_path)) 632 | return cls 633 | 634 | if not mimetypes.inited: 635 | mimetypes.init() # try to read system mime.types 636 | extensions_map = mimetypes.types_map.copy() 637 | extensions_map.update({ 638 | '': 'application/octet-stream', # Default 639 | '.py': 'text/plain', 640 | '.c': 'text/plain', 641 | '.h': 'text/plain', 642 | }) 643 | 644 | class WSGIServerHandler: 645 | def __init__(self, request_handler, stdin, stdout, stderr, environ, 646 | multithread=True, multiprocess=False): 647 | self.request_handler = request_handler 648 | self.stdin = stdin 649 | self.stdout = stdout 650 | self.stderr = stderr 651 | self.base_env = environ 652 | self.wsgi_multithread = multithread 653 | self.wsgi_multiprocess = multiprocess 654 | self.request_handler = None 655 | self.headers_sent = False 656 | self._send_buffer = b"" 657 | 658 | def setup_environ(self): 659 | env = self.environ = self.base_env.copy() 660 | env['wsgi.input'] = self.stdin 661 | env['wsgi.errors'] = self.stderr 662 | # env['wsgi.version'] = self.wsgi_version 663 | # env['wsgi.run_once'] = self.wsgi_run_once 664 | env['wsgi.multithread']= self.wsgi_multithread 665 | env['wsgi.multiprocess'] = self.wsgi_multiprocess 666 | 667 | def handle_error(self, e): 668 | self.request_handler.server.handle_exception(e, 669 | self.request_handler.request) 670 | 671 | def run(self, application): 672 | try: 673 | self.setup_environ() 674 | self.result = application(self.environ, self.start_response) 675 | self.finish_response() 676 | except Exception as e: 677 | self.handle_error(e) 678 | 679 | def start_response(self, status, headers): 680 | self.status = status.strip() 681 | self.headers = self.format_headers(headers) 682 | self.headers.update(self.request_handler.headers) 683 | 684 | assert type(status)==str, "Status must a str type" 685 | assert len(status)>=4,"Status must be at least 4 characters" 686 | assert int(status[:3]),"Status message must begin w/3-digit code" 687 | assert status[3]==" ", "Status message must have a space after code" 688 | return self.write 689 | 690 | def finish_response(self): 691 | try: 692 | for data in self.result: 693 | if type(data) == str: data = data.encode('utf-8', replace) 694 | self._send_buffer += data 695 | self.write(self._send_buffer) 696 | finally: 697 | pass 698 | 699 | def format_headers(self, headers): 700 | return dict(list(headers)) 701 | def set_header(self, key, val): 702 | self.headers[key] = val 703 | 704 | def send_headers(self): 705 | if 'Content-Length' not in self.headers: 706 | self.set_header('Content-Length', len(self._send_buffer)) 707 | _headers = "{} {}\r\n".format(self.environ['SERVER_PROTOCOL'], self.status) 708 | for k, v in self.headers.items(): 709 | _headers += "{}: {}\r\n".format(k, v) 710 | _headers += "\r\n" 711 | self._write(_headers) 712 | 713 | def close(self): 714 | self.request_handler.close() 715 | 716 | def _write(self, data): 717 | self.stdout.write(data) 718 | 719 | def write(self, data): 720 | if not self.headers_sent: 721 | self.send_headers() 722 | self._write(data) 723 | 724 | def flush(self): 725 | '''return True if all data has been sent''' 726 | return not bool(self.request_handler.iostream._write_buffer) 727 | 728 | class WSGIRequestHandler(BaseHTTPRequestHandler): 729 | server_version = "WSGIServer/0.2" 730 | class STDOUT: 731 | def flush(self): pass 732 | def close(self): self.write = lambda d:0 733 | 734 | def get_environ(self): 735 | env = self.server.base_environ.copy() 736 | env['SERVER_PROTOCOL'] = self.http_version 737 | env['SERVER_SOFTWARE'] = self.server_version 738 | env['REQUEST_METHOD'] = self.command 739 | url_parse = urlparse(self.request_url) 740 | env['PATH_INFO'] = url_parse.path 741 | env['QUERY_STRING'] = url_parse.query 742 | env['wsgi.url_scheme']= url_parse.scheme 743 | env['HTTP_HOST']= url_parse.netloc 744 | return env 745 | 746 | def get_stderr(self): 747 | return sys.stderr 748 | 749 | def _run(self): 750 | data_ready = self.iostream.read() 751 | if data_ready and self.verify_request(): 752 | if self.parse_request(): 753 | # prg = self.dataReceived() 754 | stdout = self.STDOUT() 755 | setattr(stdout, 'write', self._write) 756 | handler = WSGIServerHandler( 757 | self, io.StringIO(self.request_body), stdout, self.get_stderr(), self.get_environ() 758 | ) 759 | handler.request_handler = self 760 | handler.run(self.server.get_app()) 761 | if not self.keep_alive: self.close() 762 | 763 | class WSGIAppHandler: 764 | def __init__(self, environ, get_handler): 765 | self.base_environ = environ.copy() 766 | self.get_handler = get_handler 767 | self._write = None 768 | self.handler = None 769 | self.result = [] 770 | self.parameters = {} 771 | self.environ = {'set_header': self.set_header, 772 | 'set_response_status':self.set_response_status} 773 | self.headers = {} 774 | self.respond_status = 200 775 | self.init_response() 776 | 777 | def set_header(self, opt, val): 778 | self.headers[opt] = val 779 | 780 | def set_response_status(self, code): 781 | assert type(code) == int 782 | self.respond_status = code 783 | 784 | def init_response(self): 785 | self.environ['request_path'] = self.request_path = self.base_environ['PATH_INFO'] 786 | self.environ['request_version'] = self.request_version = self.base_environ['SERVER_PROTOCOL'] 787 | self.environ['url_scheme'] = self.url_scheme = self.base_environ['wsgi.url_scheme'] 788 | self.environ['request_query'] = self.request_query = self.base_environ['QUERY_STRING'] 789 | self.environ['request_connection_type'] = self.request_connection_type = self.base_environ.get('HTTP_CONNECTION') 790 | self.environ['run_once'] = self.run_once = self.base_environ.get('wsgi.run_once') 791 | self.environ['multiprocess'] = self.multiprocess = self.base_environ.get('wsgi.multiprocess') 792 | self.environ['stdin'] = self.stdin = self.base_environ['wsgi.input'] 793 | self.environ['host'] = self.host = self.base_environ['HTTP_HOST'] 794 | self.environ['stderr'] = self.stderr = self.base_environ['wsgi.errors'] 795 | self.environ['command'] = self.command = self.base_environ['REQUEST_METHOD'] 796 | self.environ['multithread'] = self.multithread = self.base_environ.get('wsgi.multithread') 797 | 798 | if self.request_query: 799 | self.parameters = parse_qs(self.request_query) 800 | if self.command == 'POST': 801 | # TODO large body 802 | self.environ['request_body'] = self.request_body = self.stdin.read(65536) 803 | self.parameters.update(parse_qs(self.request_body)) 804 | self.environ['parameters'] = self.parameters 805 | self.environ['write'] = self.write 806 | self.environ['send_error'] = self.send_error 807 | 808 | def write(self, data): 809 | if type(data) == str: 810 | data = data.encode('utf-8') 811 | self.result.append(data) 812 | 813 | def send_error(self, code, msg): 814 | self.set_response_status(code) 815 | self.stderr.write(msg) 816 | return msg 817 | 818 | def get_headers(self): 819 | if "Content-Type" not in self.headers: 820 | self.headers["Content-Type"] = "text/html; charset=UTF-8" 821 | return list(self.headers.items()) 822 | 823 | def process(self): 824 | '''return (status, headers_list)''' 825 | handler, args = self.get_handler(self.request_path) 826 | if hasattr(handler, self.command.lower()): 827 | ins = handler(self.environ) 828 | res = getattr(ins, self.command.lower())(*args) 829 | if type(res) == types.GeneratorType: 830 | for _data in res: self.write(_data) 831 | else: 832 | if res: self.write(res) 833 | 834 | if hasattr(handler, 'code'): 835 | code = int(getattr(handler, 'code')) 836 | status = "{} {}".format(code, BaseHTTPRequestHandler.RESPONSES_CODE.get(code, "???")) 837 | else: status = "{} {}".format(self.respond_status, 838 | BaseHTTPRequestHandler.RESPONSES_CODE.get(self.respond_status, "???")) 839 | headers = self.get_headers() 840 | else: 841 | status = "501 Not Implemented" 842 | headers = [('Content-Type', 'text/html; charset=UTF-8')] 843 | return status, headers 844 | 845 | def finish_response(self, write_func): 846 | '''return results_list''' 847 | if write_func: self._write = write_func 848 | return self.result 849 | 850 | class BaseIOStream: 851 | MAX_READ_SIZE = 2097152 852 | MAX_CHUNK_SIZE = 65536 853 | _ERRNO_WOULDBLOCK = (errno.EWOULDBLOCK, errno.EAGAIN) 854 | if hasattr(errno, "WSAEWOULDBLOCK"): 855 | _ERRNO_WOULDBLOCK += (errno.WSAEWOULDBLOCK,) 856 | 857 | _ERRNO_CONNRESET = (errno.ECONNRESET, errno.ECONNABORTED, errno.EPIPE, 858 | errno.ETIMEDOUT) 859 | if hasattr(errno, "WSAECONNRESET"): 860 | _ERRNO_CONNRESET += (errno.WSAECONNRESET, errno.WSAECONNABORTED, 861 | errno.WSAETIMEDOUT) 862 | 863 | def __init__(self, request, server): 864 | self.request = request 865 | self.server = server 866 | self._read_buffer = b"" 867 | self._write_buffer = b"" 868 | 869 | def read(self): 870 | try: chunk = self.request.recv(self.MAX_CHUNK_SIZE) 871 | except (socket.error, IOError, OSError) as e: 872 | if errno_from_exception(e) in self._ERRNO_WOULDBLOCK: 873 | pass 874 | else: 875 | self.server.handle_exception(e, self.request) 876 | return False 877 | # TODO shutdown_request when buffer > MAX_READ_SIZE 878 | else: 879 | if chunk: self._read_buffer += chunk 880 | else: 881 | self.server.shutdown_request(self.request) 882 | return False 883 | return True 884 | 885 | def write(self, data): 886 | if type(data) == str: data = data.encode('utf-8') 887 | sent = 0 888 | while True: 889 | try: sent = self.request.send(data) 890 | except (socket.error, IOError, OSError) as e: 891 | if errno_from_exception(e) in self._ERRNO_WOULDBLOCK: 892 | self._write_buffer += data 893 | return False 894 | else: 895 | self.server.handle_exception(e, self.request) 896 | return True 897 | else: 898 | # logging.debug('directly sent: {}'.format(sent)) 899 | if sent < len(data): data = data[sent:] 900 | else: return True 901 | 902 | class DictHeapq: 903 | class _node(object): 904 | def __init__(self, k, v, f): self.k, self.v, self.f = k, v, f 905 | def __cmp__(self, o): return self.f > o.f 906 | def __lt__(self, o): return self.f < o.f 907 | def __eq__(self, o): return self.f == o.f 908 | def __init__(self, size): 909 | self.size, self.f = size, 0 910 | self._dict, self._heap = {}, [] 911 | def __contains__(self, k): return k in self._dict 912 | def __setitem__(self, k, v): 913 | if k in self._dict: 914 | n = self._dict[k] 915 | n.v = v 916 | self.f += 1 917 | n.f = self.f 918 | heapq.heapify(self._heap) 919 | else: 920 | while len(self._heap) >= self.size: 921 | del self._dict[heapq.heappop(self._heap).k] 922 | self.f = 0 923 | for n in self._heap: n.f = 0 924 | n = self._node(k, v, self.f) 925 | self._dict[k] = n 926 | heapq.heappush(self._heap, n) 927 | def __getitem__(self, k): 928 | n = self._dict[k] 929 | self.f += 1 930 | n.f = self.f 931 | heapq.heapify(self._heap) 932 | return n.v 933 | def __delitem__(self, k): 934 | n = self._dict[k] 935 | del self._dict[k] 936 | self._heap.remove(n) 937 | heapq.heapify(self._heap) 938 | return n.v 939 | def __iter__(self): 940 | c = self._heap[:] 941 | while len(c): yield heapq.heappop(c).k 942 | raise StopIteration 943 | 944 | def cache_template(func): 945 | _cache = {} 946 | # use DictHeapq as cache for a large mount templates 947 | # _cache = DictHeapq(1000) 948 | 949 | def _(self, *args, **kwargs): 950 | tplid = (str(self.lookup.sort()), self.filename) 951 | if tplid in _cache: 952 | res = _cache[tplid] 953 | else: 954 | res = func(self, *args, **kwargs) 955 | _cache[tplid] = res 956 | return res 957 | return _ 958 | 959 | class BaseTemplate: 960 | pattern = re.compile('{{(.*?)}}') 961 | def __init__(self, source=None, filename=None, lookup=['templates'], **kwargs): 962 | self.source = source 963 | self.filename = filename 964 | self.lookup = lookup 965 | self.kwargs = kwargs 966 | self.encoding = 'utf-8' 967 | self.env = {} 968 | self.prepare() 969 | 970 | def prepare(self, **kwargs): 971 | if not self.source: 972 | self.source = self.get_source() 973 | 974 | @cache_template 975 | def get_source(self): 976 | path = "" 977 | for tpl_path in self.lookup: 978 | full_path = os.path.join(os.path.dirname( 979 | os.path.abspath(__file__)), tpl_path, self.filename) 980 | if os.path.isfile(full_path): 981 | path = full_path 982 | break 983 | if not path: 984 | raise ValueError("can't find template: {}".format(self.filename)) 985 | source = open(path, 'rb').read().decode('utf-8') 986 | return source 987 | 988 | def repl(self, match): 989 | code = match.group(1).strip() 990 | if " for " in code: code = "[{}]".format(code) 991 | if code: 992 | res = eval(code, self.env) 993 | if type(res) == list: res = "".join(map(str, res)) 994 | else: res = str(res) 995 | return res 996 | 997 | def render(self, *args, **kwargs): 998 | # return "good" 999 | self.env = {} 1000 | if type(args[0]) == dict: self.env.update(args[0]) 1001 | self.env.update(kwargs) 1002 | return self.pattern.sub(self.repl, self.source) 1003 | 1004 | class MakoTemplate(BaseTemplate): 1005 | def prepare(self, **options): 1006 | from mako.template import Template 1007 | from mako.lookup import TemplateLookup 1008 | options.update({'input_encoding':self.encoding}) 1009 | lookup = TemplateLookup(directories=self.lookup, **options) 1010 | if self.source: 1011 | self.tpl = Template(self.source, lookup=lookup, **options) 1012 | else: 1013 | self.tpl = Template( filename=self.filename, lookup=lookup, **options) 1014 | 1015 | def render(self, *args, **kwargs): 1016 | for dictarg in args: kwargs.update(dictarg) 1017 | _defaults = self.env.copy() 1018 | _defaults.update(kwargs) 1019 | return self.tpl.render(**_defaults) 1020 | 1021 | def template(*args, **kwargs): 1022 | if not args: raise ValueError 1023 | template_lookup = ['.', 'templates'] 1024 | tpl = args[0] 1025 | for cfg in args[1:]: 1026 | if type(cfg) == dict: 1027 | kwargs.update(cfg) 1028 | adapter = kwargs.pop('template_adapter', BaseTemplate) 1029 | lookup = kwargs.pop('template_lookup', template_lookup) 1030 | settings = kwargs.pop('template_settings', {}) 1031 | if isinstance(tpl, adapter): 1032 | temp = tpl 1033 | elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl: 1034 | temp = adapter(source=tpl, lookup=lookup, *settings) 1035 | else: 1036 | temp = adapter(filename=tpl, lookup=lookup, *settings) 1037 | return temp.render(kwargs) 1038 | 1039 | mako_template = functools.partial(template, template_adapter=MakoTemplate) 1040 | 1041 | class Graily: 1042 | def __init__(self, handlers, **settings): 1043 | self.server = None 1044 | self.handlers = [(re.compile(r'^.*$'), NotFoundHandler)] 1045 | self.parse_handlers(handlers) 1046 | 1047 | def parse_handlers(self, handlers): 1048 | for _h, _f in handlers: 1049 | self.handlers.insert(-1, (re.compile(_h), _f)) 1050 | 1051 | def get_handler(self, url): 1052 | for _h, _f in self.handlers: 1053 | match = _h.match(url) 1054 | if match: 1055 | return _f, match.groups() 1056 | return False, () 1057 | 1058 | def server_bind(self, server_address, request_class=BaseHTTPRequestHandler): 1059 | setattr(request_class, 'get_handler', self.get_handler) 1060 | # self.server = HTTPServer(server_address, request_class) 1061 | self.server = ThreadPollTCPServer(server_address, request_class) 1062 | 1063 | def serve_forever(self): 1064 | return self.server.serve_forever() 1065 | 1066 | def wsgi(self, environ, start_response): 1067 | # for k,v in environ.items(): 1068 | # print(k,v) 1069 | 1070 | handler = WSGIAppHandler(environ, self.get_handler) 1071 | try: status, headers = handler.process() 1072 | except: 1073 | status = "500 Internal Server Error" 1074 | headers = [("Content-Type", "text/plain; charset=UTF-8")] 1075 | start_response(status, headers, sys.exc_info()) 1076 | result = [] 1077 | else: 1078 | result = handler.finish_response(start_response(status, headers)) 1079 | return result 1080 | 1081 | def __call__(self, environ, start_response): 1082 | return self.wsgi(environ, start_response) 1083 | 1084 | def errno_from_exception(err): 1085 | if hasattr(err, 'errno'): return err.errno 1086 | elif err.args: return err.args[0] 1087 | 1088 | def _quote_html(html): 1089 | return html.replace("&", "&").replace("<", "<").replace(">", ">") 1090 | 1091 | def init_log(**kwargs): 1092 | config = {'format': '%(asctime)s %(levelname)s %(message)s', 1093 | 'level': logging.INFO, 1094 | } 1095 | config.update(kwargs) 1096 | logging.basicConfig(**config) 1097 | 1098 | def make_server(server_address, app, server_class=WSGIServer, 1099 | handler_class=WSGIRequestHandler): 1100 | server = server_class(server_address, handler_class) 1101 | server.set_app(app) 1102 | return server 1103 | --------------------------------------------------------------------------------