def __init__(self, **kwargs): self.form = WebControlFormHelper(**kwargs) self.logger = kwargs.get('logger',) self.robot = kwargs.get('robot') #initialize speed in form with robot speed self.form.speed = self.robot.setDriveSpeed #create routes to web pages self.router = PathRouter() self.router.add_routes([ url('/', self.do_main_page, name='home'), url('/doRobotControl', self.do_process_form, name='execute'), url('/showRobotControlForm', self.do_display_form, name='view') ])
def get_routes(self, path='', iden_format=r'(?P<iden>\w+)'): ''' Prepare routes for the given REST resource :param path: string -- base path for the REST resource :param iden: string -- format for identifier, for instance might be used to make composite identifier ''' return [ url(r'^{}(?:\.(?P<data_format>\w+))?$'.format(path), self.wrap_request), url( r'^{}/{}(?:\.(?P<data_format>\w+))?$'.format( path, iden_format), self.wrap_request) ]
def get_routes(self, path='', iden_format='(?P<iden>\w+)'): ''' Prepare routes for the given REST resource :param path: string -- base path for the REST resource :param iden: string -- format for identifier, for instance might be used to make composite identifier ''' return [ url( r'^{}(?:\.(?P<data_format>\w+))?$'.format(path), self.wrap_request ), url( r'^{}/{}(?:\.(?P<data_format>\w+))?$'.format( path, iden_format), self.wrap_request ) ]
def __init__(self, **kwargs): super(MancifyWsgiApp, self).__init__() self.sms = MancifySMSService(kwargs['clockwork_api_key']) self.exec_timeout = kwargs.get('exec_timeout', 10) self.connect_timeout = kwargs.get('connect_timeout', 30) self.session_timeout = kwargs.get('session_timeout', 300) self.output_limit = kwargs.get('output_limit', 1024) self.router = PathRouter() self.router.add_routes([ url('/', self.do_index), url('/ssh', self.do_ssh), url('/translate', self.do_translate), ]) self.lock = threading.Lock() self.sessions = {} self.messages = set() self.terminate = threading.Event() self.reap_thread = threading.Thread(target=self.reap_sessions) self.reap_thread.daemon = True self.reap_thread.start()
""" """ from wheezy.routing import url from public.web.urls import error_urls from public.web.urls import public_urls from public.web.urls import static_urls from public.web.views import WelcomeHandler locale_pattern = '{locale:(en|ru)}/' locale_defaults = {'locale': 'en'} locale_urls = [] locale_urls += public_urls locale_urls.append(('error/', error_urls)) locale_urls.append(('.*', lambda ignore: None)) all_urls = [ url('', WelcomeHandler, locale_defaults), url(locale_pattern.rstrip('/'), WelcomeHandler, locale_defaults, name='default'), (locale_pattern, locale_urls, locale_defaults), ] all_urls += static_urls
pq[:, :-needed] = q result = index.search(padded, pq, K = k, withDistance = True) ids = map(lambda x: pids[x], result[0][0].tolist()) return self.json_response({'ids': ids, 'dists': result[1][0].tolist()}) def welcome(request): response = HTTPResponse() response.write('Server is up!') return response all_urls = [ url('', welcome, name='default'), url('search', SearchHandler, name='search') ] options = {} web = WSGIApplication( middleware=[ bootstrap_defaults(url_mapping=all_urls), path_routing_middleware_factory ], options=options ) indices = {}
for f in fortunes: f.message = bleach.clean(f.message) template_html = template.render({"fortunes": fortunes}) response = HTTPResponse() response.write(template_html) return response def plaintext(request): response = HTTPResponse() response.headers = [("Content-Type", "text/plain; charset=UTF-8")] response.write("Hello, world!") return response all_urls = [ url("plaintext", plaintext, name="plaintext"), url("json", JsonHandler, name="json"), url("db", DbHandler, name="db"), url("queries", QueriesHandler, name="queries"), url("updates", UpdatesHandler, name="updates"), url("fortune", FortuneHandler, name="fortune") ] options = {} app = WSGIApplication( middleware = [ bootstrap_defaults(url_mapping=all_urls), path_routing_middleware_factory ], options = options
def get(self): rows = find_all() response = HTTPResponse() response.write(rows) return response def post(self): data = self.request.form insert(data) response = HTTPResponse() response.status_code = 201 return response all_urls = [ url('', DatabaseHandler, name='database'), url('hello', HelloHandler, name='hello'), ] main = WSGIApplication( middleware=[bootstrap_defaults(url_mapping=all_urls), path_routing_middleware_factory], options={} ) if __name__ == '__main__': bjoern.listen(main, '0.0.0.0', 8080) bjoern.run()
from wheezy.web.handlers import BaseHandler from wheezy.web.middleware import bootstrap_defaults from wheezy.web.middleware import path_routing_middleware_factory import ujson class WelcomeHandler(BaseHandler): def get(self): response = HTTPResponse(content_type="application/json; charset=UTF-8") response.write(ujson.dumps({"test": True})) return response all_urls = [ url("", WelcomeHandler, name="default"), # url('', welcome, name='welcome') ] options = {} main = WSGIApplication( middleware=[ bootstrap_defaults(url_mapping=all_urls), path_routing_middleware_factory, ], options=options, ) if __name__ == "__main__": import sys from wsgiref.simple_server import make_server
class Home(BaseHandler): def get(self): return self.render_response('templates/test.html') class Api(BaseHandler): def get(self): if self.request.environ.get('wsgi.websocket'): ws = self.request.environ['wsgi.websocket'] while True: message = ws.receive() ws.send(message) return all_urls = [url('', Home), url('api', Api)] options = {} # Template Engine searchpath = [''] engine = Engine(loader=FileLoader(searchpath), extensions=[ CoreExtension(), ]) engine.global_vars.update({'h': html_escape}) options.update({'render_template': WheezyTemplate(engine)}) main = WSGIApplication(middleware=[ bootstrap_defaults(url_mapping=all_urls), path_routing_middleware_factory ],
def url_index(path, name=None): return url(path, static, {'path': 'index.html'}, name=name)
""" """ from wheezy.routing import url from membership.web.urls import membership_urls from public.web.urls import error_urls from public.web.urls import public_urls from public.web.urls import static_urls from public.web.views import home locale_pattern = '{locale:(en|ru)}/' locale_defaults = {'locale': 'en'} locale_urls = public_urls + membership_urls locale_urls.append(('error/', error_urls)) all_urls = [ url('', home, locale_defaults, name='default'), (locale_pattern, locale_urls, locale_defaults), ] all_urls += static_urls
from wheezy.http import HTTPResponse, WSGIApplication from wheezy.routing import url from wheezy.web.handlers import BaseHandler from wheezy.web.middleware import bootstrap_defaults from wheezy.web.middleware import path_routing_middleware_factory from config import PING_MESSAGE class Ping(BaseHandler): def get(self): response = HTTPResponse() response.write(PING_MESSAGE.format(app='wheezyweb')) return response app = WSGIApplication(middleware=[ bootstrap_defaults([url('', Ping)]), path_routing_middleware_factory ], options={})
from wheezy.http import WSGIApplication from wheezy.routing import url from wheezy.web.handlers import BaseHandler from wheezy.web.middleware import bootstrap_defaults from wheezy.web.middleware import path_routing_middleware_factory class WelcomeHandler(BaseHandler): def get(self): response = HTTPResponse() response.write('Hello World!') return response def welcome(request): response = HTTPResponse() response.write('Hello World!') return response all_urls = [ url('welcome', WelcomeHandler), #url('welcome', welcome), ] warnings.simplefilter('ignore') main = WSGIApplication(middleware=[ bootstrap_defaults(url_mapping=all_urls), path_routing_middleware_factory ], options={})
if token_response.status_code == 200: json_response = token_response.json() refresh_token = json_response["refresh_token"] encrypted_token = crypt.encrypt(refresh_token) json_response["refresh_token"] = encrypted_token response_body = json.dumps(json_response) response.write(response_body) else: response.write_bytes(token_response.content) return response all_urls = [ url(config.APP_REFRESH_PATH, RefreshHandler, name='refresh'), url(config.APP_SWAP_PATH, SwapHandler, name='swap'), ] options = {'render_template': None, 'ticket': Ticket(digestmod=sha256)} main = WSGIApplication(middleware=[ bootstrap_defaults(url_mapping=all_urls), path_routing_middleware_factory ], options=options) if __name__ == '__main__': from wsgiref.simple_server import make_server try: print('Visit http://localhost:8080/') make_server('', 8080, main).serve_forever() except KeyboardInterrupt:
'msg_type': 'message', 'nickname': message['nickname'], 'message': message['message'] })) def on_close(self, reason): print "Connection closed! " class Home(BaseHandler): def get(self): return self.render_response('templates/chat.html') all_urls = [ url('', Home), url('static/{path:any}', file_handler(root='static/'), name='static') ] options = {} # Template Engine searchpath = [''] engine = Engine(loader=FileLoader(searchpath), extensions=[ CoreExtension(), ]) engine.global_vars.update({'h': html_escape}) options.update({'render_template': WheezyTemplate(engine)}) main = WSGIApplication(middleware=[
""" """ from wheezy.routing import url from public.web.views import WelcomeHandler from public.web.views import http400 from public.web.views import http403 from public.web.views import http404 from public.web.views import http500 from public.web.views import static_file public_urls = [url('home', WelcomeHandler, name='home')] error_urls = [ url('400', http400, name='http400'), url('403', http403, name='http403'), url('404', http404, name='http404'), url('500', http500, name='http500'), ] static_urls = [ url('static/{path:any}', static_file, name='static'), url('favicon.ico', static_file, {'path': 'img/favicon.ico'}) ] # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
from wheezy.web.handlers import BaseHandler from wheezy.web.middleware import bootstrap_defaults from wheezy.web.middleware import path_routing_middleware_factory import json def welcome(request): response = HTTPResponse() response.write('Hello World!') return response def json_view(request): response = HTTPResponse() json_data = {"message": "Hello, World!"} data = json.dumps(json_data) response.write(data) return response all_urls = [ url('', welcome, name='default'), url('json', json_view, name='json_view') ] options = {} app = WSGIApplication(middleware=[ bootstrap_defaults(url_mapping=all_urls), path_routing_middleware_factory ], options=options)
def __init__(self, **kwargs): super().__init__() self.library = PicroscopyLibrary(**kwargs) self.helpers = WebHelpers(self.library) self.clients = kwargs.get('clients', IPv4Network('0.0.0.0/0')) logging.info('Clients must be on network %s', self.clients) self.static_dir = os.path.abspath( os.path.normpath( kwargs.get('static_dir', os.path.join(HERE, 'static')))) logging.info('Static files: %s', self.static_dir) self.templates_dir = os.path.abspath( os.path.normpath( kwargs.get('templates_dir', os.path.join(HERE, 'templates')))) logging.info('Chameleon templates: %s', self.templates_dir) self.templates = PageTemplateLoader(self.templates_dir, default_extension='.pt') self.layout = self.templates['layout'] # No need to make flashes a per-session thing - it's a single user app! self.flashes = [] self.router = PathRouter() # XXX Add handler for exiting system # XXX Make exit code conditional? (upgrade/reboot/shutdown/etc.) self.router.add_routes([ url('/', self.do_template, kwargs={'page': 'library'}, name='home'), url('/{page}.html', self.do_template, name='template'), url('/view/{image}.html', self.do_template, kwargs={'page': 'image'}, name='view'), url('/static/{path:any}', self.do_static, name='static'), url('/images/{image}', self.do_image, name='image'), url('/thumbs/{image}', self.do_thumb, name='thumb'), url('/delete/{image}', self.do_delete, name='delete'), url('/config', self.do_config, name='config'), url('/reset', self.do_reset, name='reset'), url('/capture', self.do_capture, name='capture'), url('/download', self.do_download, name='download'), url('/send', self.do_send, name='send'), url('/logout', self.do_logout, name='logout'), ])
""" """ from wheezy.routing import url from shared.views import url_index from posts.web.views import PostHandler from posts.web.views import PostCommentsHandler from posts.web.views import SearchPostsHandler posts_api_urls = [ url("search/posts", SearchPostsHandler), url("post/{slug}", PostHandler), url("post/{slug}/comments", PostCommentsHandler), ] posts_urls = [url_index("posts", name="posts"), url_index("post/{slug}", name="post")]
parts = addr.split(':') try: socket.getaddrinfo(parts[0], parts[1]) except (IndexError, socket.error, socket.herror, socket.gaierror, socket.timeout): raise InvalidServerAddress(addr) class InvalidServerAddress(Exception): def __init__(self, addr): super(InvalidServerAddress, self).__init__('Invalid address specified: %s' % addr) url_map = [ url('', MainView, name='index'), url('static/{path:any}', file_handler(root=config.app_path('static/')), name='static'), ] application = WSGIApplication(middleware=[ bootstrap_defaults(url_mapping=url_map), path_routing_middleware_factory ], options=config.options) if __name__ == '__main__': from wsgiref.simple_server import make_server try: LOG.info('Launching on http://localhost:5000/ ...') make_server('', 5000, application).serve_forever()
"You are successfully added. We will invite on the beta launch" }) else: return self.json_response({ 'success': "We will invite on the beta launch", 'error': "You are already registered." }) else: return self.json_response( {'error': "Wrong Email Address. Please Correct yourself."}) all_urls = [ url('', HomePage, name='default'), url('email', EmailPage, name='email'), url('static/{path:any}', file_handler(root='static/'), name='static') ] options = {} # Template Engine searchpath = [''] engine = Engine(loader=FileLoader(searchpath), extensions=[ CoreExtension(), WidgetExtension(), ]) engine.global_vars.update({'h': html_escape}) options.update({'render_template': WheezyTemplate(engine)})
import os from wheezy.routing import url import importlib from rit.core.dynamic_content.views import testdynamiccomponent all_urls = [ url('testdynamiccomponent', testdynamiccomponent, name='testdynamiccomponent'), ] project_settings_module = os.getenv('RIT_SETTINGS_MODULE') if project_settings_module: url_mod = importlib.import_module( project_settings_module.replace('settings', 'urls')) all_urls.extend(url_mod.urls)
from wheezy.routing import url from wheezy.web.handlers import file_handler from views import AddHandler from views import ListHandler all_urls = [ url('', ListHandler, name='list'), url('add', AddHandler, name='add'), url('static/{path:any}', file_handler(root='static/'), name='static') ]
class WelcomeHandler(BaseHandler): def get(self): response = HTTPResponse() response.write('Hello World!') return response def welcome(request): response = HTTPResponse() response.write('Hello World!') return response all_urls = [ url('', WelcomeHandler, name='default'), url('welcome', welcome, name='welcome') ] options = {} # Security options.update({ 'ticket': Ticket(max_age=config.getint('crypto', 'ticket-max-age'), salt=config.get('crypto', 'ticket-salt'), cypher=aes128, digestmod=ripemd160 or sha256 or sha1, options={ 'CRYPTO_ENCRYPTION_KEY': config.get('crypto', 'encryption-key'), 'CRYPTO_VALIDATION_KEY': config.get('crypto', 'validation-key') }),
""" surabayapy-facebook-bot oleh Christoforus Surjoputro ~~~~~~~~~ Modul url untuk meyimpan handler apa saja yang terdapat pada modul chat :license: MIT, see LICENSE for more details. """ from wheezy.routing import url from chat.web.api import Chat chat_urls = [url('chat', Chat, name='chat')]
from gevent import pywsgi from wheezy.http import HTTPResponse from wheezy.http import WSGIApplication from wheezy.routing import url from wheezy.web.handlers import BaseHandler from wheezy.web.middleware import bootstrap_defaults from wheezy.web.middleware import path_routing_middleware_factory def test(request): response = HTTPResponse() response.write('<html><body>Hello World</body></html>') return response routes = [ url('test', test, name='test') ] options = {} main = WSGIApplication( middleware=[ bootstrap_defaults(url_mapping=routes), path_routing_middleware_factory ], options=options ) server = pywsgi.WSGIServer(('127.0.0.1', 5000), main, backlog=128000) server.serve_forever()
this.src=this.src.replace(/&r=\d+/g,'') + '&r=' + \ Math.floor(Math.random() * 100 + 1); }; } </script> </body></html>""" } engine = Engine( loader=DictLoader(templates), extensions=[CoreExtension(), WidgetExtension(), WhitespaceExtension()]) all_urls = [('', WelcomeHandler), url('captcha.jpg', captcha_handler, name='captcha')] options = {'http_cache': cache, 'render_template': WheezyTemplate(engine)} main = WSGIApplication([ bootstrap_defaults(url_mapping=all_urls), http_cache_middleware_factory, path_routing_middleware_factory ], options) if __name__ == '__main__': from wsgiref.handlers import BaseHandler from wsgiref.simple_server import make_server try: print('Visit http://localhost:8080/') BaseHandler.http_version = '1.1' make_server('', 8080, main).serve_forever() except KeyboardInterrupt:
auto_reload=True) render_template = Jinja2Template(env) # handlers from rkt import hello from caelus import main from prestige import main from slots import lucky try: index = __import__(theme) except ImportError, e: index = hello all_urls = [ url('', getattr(index.main, 'IndexHandler', hello.IndexHandler), name='default'), url('welcome', hello.welcome, name='welcome'), #url('static/{path:any}', file_handler(root='static/'), name='static') url('play', getattr(index.main, 'PlayHandler', hello.IndexHandler), name='play'), url('static/swfobject/{path:any}', file_handler(root='static/swfobject/'), name='static_swfobject'), url('static/swf/{path:any}', file_handler(root='static/swf/'), name='static_swf'), url('s/swz/{path:any}', file_handler(root='static/swf/'), name='compat_swz'), ] all_urls += _config.all_urls[theme] options = { 'XSRF_NAME': '_x', 'render_template': render_template, }
class InvalidLineError(Exception): def __init__(self, line_obj, exc): super(InvalidLineError, self).__init__() self.line = line_obj self.exc = exc def __str__(self): msg = [] for v in self.line.values(): msg.append(unicode(v)) msg.append(unicode(self.exc)) return u' | '.join(msg) url_map = [ url('', MainView, name='index'), url('static/{path:any}', file_handler(root=config.app_path('static/')), name='static'), ] application = WSGIApplication( middleware=[ bootstrap_defaults(url_mapping=url_map), path_routing_middleware_factory ], options=config.options) if __name__ == '__main__': from wsgiref.simple_server import make_server try:
def now(request): response = HTTPResponse() response.write('It is %s.' % datetime.now().time().strftime('%H:%M:%S')) return response @response_cache(public_cache_profile) def now2(request): response = HTTPResponse() response.write('It is %s.' % datetime.now().time().strftime('%H:%M:%S')) return response all_urls = [ url('', WelcomeHandler), url('welcome2', Welcome2Handler), url('now', now), url('now2', now2) ] options = {'http_cache': cache} main = WSGIApplication( middleware=[ bootstrap_defaults(url_mapping=all_urls), http_cache_middleware_factory, http_error_middleware_factory, path_routing_middleware_factory ], options=options)
from wheezy.web.handlers import file_handler from wheezy.routing import url from caelus import main as caelus_main from prestige import main as prestige_main import os base_dir = 'prestige' theme = 'prestige' env = 'live' if os.environ.get('LIVE') else 'stage' all_urls = { 'caelus':[ url('static/{path:any}', file_handler(root='caelus/static/'), name='static_caelus'), url('(?P<path>.+\.png)', file_handler(root='caelus/'), name='static_png'), url('{path:favicon.ico}', file_handler(root='caelus/'), name='static_favicon'), url('early', caelus_main.EarlyHandler, name="early"), ], 'rkt':[ url('static/{path:any}', file_handler(root='static/'), name='static') ], 'prestige':[ url('static/v/{path:any}', prestige_main.VideoHandler, name='static_movie'), url('static/js/{path:any}', file_handler(root='prestige/static/js/'), name='static_js'), url('static/i/{path:any}', file_handler(root='prestige/static/i/'), name='static_i'), url('static/css/{path:any}', file_handler(root='prestige/static/css/'), name='static_css'), url('static/fonts/{path:any}', file_handler(root='prestige/static/fonts/'), name='static_font'), url('(?P<path>.+\.png)', file_handler(root='prestige/'), name='static_png'), url('early', prestige_main.EarlyHandler, name="early"), url('payment', prestige_main.PaymentHandler, name="payment"), url('thankyou', prestige_main.ReceiptHandler, name="thankyou"), ],
from wheezy.http import HTTPResponse from wheezy.http import WSGIApplication from wheezy.routing import url from wheezy.web.handlers import BaseHandler from wheezy.web.middleware import bootstrap_defaults from wheezy.web.middleware import path_routing_middleware_factory from wheezy.web.handlers.file import file_handler from wheezy.web.handlers.base import permanent_redirect_handler , redirect_handler from datetime import timedelta import webreq import webReqHander all_urls = [ url('ping', webReqHander.PingHandler, name='ping'), url('GetServerStatus', webReqHander.GetServerStatusHandler, name='GetServerStatus'), url('NewUser', webReqHander.NewUser, name='NewUser'), url('NewTask', webReqHander.NewTask, name='NewTask'), url('UserDisable', webReqHander.UserDisable, name='UserDisable'), url('ListTask', webReqHander.ListTask, name='ListTask'), url('AchiveTask', webReqHander.AchiveTask, name='AchiveTask'), url('webui/{path:any}', file_handler( root='gui/', age=timedelta(hours=0)), name='default') ] options = {} main = WSGIApplication( middleware=[ bootstrap_defaults(url_mapping=all_urls),
from wheezy.routing import url from wheezy.web.middleware import bootstrap_defaults from wheezy.web.middleware import path_routing_middleware_factory def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n - 1) + fib(n - 2) class FibaasHandler(BaseHandler): def get(self): number = int(self.route_args["number"]) response = HTTPResponse() response.write(str(fib(number))) return response all_urls = [ url("{number}", FibaasHandler, name="fib"), ] app = WSGIApplication( middleware=[ bootstrap_defaults(url_mapping=all_urls), path_routing_middleware_factory, ], options={} )
if token_response.status_code == 200: json_response = token_response.json() refresh_token = json_response["refresh_token"] encrypted_token = crypt.encrypt(refresh_token) json_response["refresh_token"] = encrypted_token response_body = json.dumps(json_response) response.write(response_body) else: response.write_bytes(token_response.content) return response all_urls = [ url(config.APP_REFRESH_PATH, RefreshHandler, name="refresh"), url(config.APP_SWAP_PATH, SwapHandler, name="swap"), ] options = {"render_template": None, "ticket": Ticket(digestmod=sha256)} main = WSGIApplication( middleware=[bootstrap_defaults(url_mapping=all_urls), path_routing_middleware_factory], options=options ) if __name__ == "__main__": from wsgiref.simple_server import make_server try: print("Visit http://localhost:8080/")
""" """ from wheezy.routing import url from public.web.views import WelcomeHandler from public.web.views import http400 from public.web.views import http403 from public.web.views import http404 from public.web.views import http500 from public.web.views import static_file public_urls = [ url('home', WelcomeHandler, name='home') ] error_urls = [ url('400', http400, name='http400'), url('403', http403, name='http403'), url('404', http404, name='http404'), url('500', http500, name='http500'), ] static_urls = [ url('static/{path:any}', static_file, name='static'), url('favicon.ico', static_file, {'path': 'img/favicon.ico'}) ]
class WelcomeHandler(BaseHandler): def get(self): response = HTTPResponse() response.write('Hello World!') return response def welcome(request): response = HTTPResponse() response.write('Hello World!') return response all_urls = [ url('', WelcomeHandler, name='default'), url('welcome', welcome, name='welcome') ] options = {} main = WSGIApplication( middleware=[ bootstrap_defaults(url_mapping=all_urls), path_routing_middleware_factory ], options=options ) if __name__ == '__main__':
def datatoZigBee(request): response = HTTPResponse() try: id= int(request.get_param('id')) data=request.get_param('data').encode("ascii") addr=dictionary[id]['addr'] addr_long=dictionary[id]['addr_long'] sendToZigBee(addr_long, addr, data) except Exception as e: print ("Error enviando datos "+ str(e)) response.status_code = 401 return response # URL mapping del Servidor all_urls = [ url('', Home, name="default"), url(r'^nodes', nodes, name='nodes'), url(r'^id', get_id, name='id'), url(r'^data', data, name='data'), url(r'^zigbee', datatoZigBee, name='zigbee'), url('static/{path:any}', file_handler(root='static/'), name='static') ] # Configuracion del servidor HTTP options = {} # Template Engine searchpath = ['templates'] engine = Engine(
""" """ from wheezy.routing import url from membership.web.views import SignInHandler from membership.web.views import SignOutHandler from membership.web.views import SignUpHandler membership_urls = [ url('signin', SignInHandler, name='signin'), url('signout', SignOutHandler, name='signout'), url('signup', SignUpHandler, name='signup'), ]
fout = open(os.path.join(conf.get('upload_dir'), savefile), 'w') fout.write(content) fout.close() response.write(conf.get('upload_url_prefix') + savefile) else: return bad_request() else: # bad request return bad_request() return response # url mapping all_urls = [ url('', ping, name='default'), url('upload', upload, name='upload') ] # for wsgi execute warnings.simplefilter('ignore') app = WSGIApplication( middleware = [ bootstrap_defaults(url_mapping=all_urls), path_routing_middleware_factory ], options={} ) # for main execute
from wheezy.routing import url from wheezy.web.handlers import BaseHandler from wheezy.web.middleware import bootstrap_defaults from wheezy.web.middleware import path_routing_middleware_factory class WelcomeHandler(BaseHandler): def get(self): response = HTTPResponse() response.write('Hello World!') return response all_urls = [ url('', WelcomeHandler, name='default'), ] options = {} application = main = WSGIApplication( middleware=[ bootstrap_defaults(url_mapping=all_urls), path_routing_middleware_factory ], options=options ) if __name__ == '__main__': from wsgiref.simple_server import make_server
""" """ from wheezy.routing import url from public.web.views import about from public.web.views import home from public.web.views import http400 from public.web.views import http403 from public.web.views import http404 from public.web.views import http500 from public.web.views import static_file public_urls = [ url('home', home, name='home'), url('about', about, name='about'), ] error_urls = [ url('400', http400, name='http400'), url('403', http403, name='http403'), url('404', http404, name='http404'), url('500', http500, name='http500'), ] static_urls = [ url('static/{path:any}', static_file, name='static'), url('favicon.ico', static_file, {'path': 'img/favicon.ico'}) ]
from wheezy.routing import url from wheezy.web.handlers import BaseHandler from wheezy.web.middleware import bootstrap_defaults from wheezy.web.middleware import path_routing_middleware_factory class WelcomeHandler(BaseHandler): @staticmethod def get(): response = HTTPResponse(content_type='application/json; charset=UTF-8') response.write(ujson.dumps({"test": True})) return response all_urls = [ url('', WelcomeHandler, name='default'), # url('', welcome, name='welcome') ] options = {} main = WSGIApplication(middleware=[ bootstrap_defaults(url_mapping=all_urls), path_routing_middleware_factory ], options=options) if __name__ == '__main__': import sys from wsgiref.simple_server import make_server try: print('Visit http://localhost:{}/'.format(sys.argv[-1]))
from wheezy.routing import url from public.web.views import DailyQuoteHandler from public.web.views import css_file from public.web.views import http400 from public.web.views import http401 from public.web.views import http403 from public.web.views import http404 from public.web.views import http500 from public.web.views import js_file from public.web.views import static_file public_api_urls = [ url('quote/daily', DailyQuoteHandler) ] public_urls = [ ] error_urls = [ url('400', http400, name='http400'), url('401', http401, name='http401'), url('403', http403, name='http403'), url('404', http404, name='http404'), url('500', http500, name='http500'), ] static_urls = [ url('js/{path:any}', js_file, name='js'),
def get(self): return self.render_response('templates/test.html') class Api(BaseHandler): def get(self): if self.request.environ.get('wsgi.websocket'): ws = self.request.environ['wsgi.websocket'] while True: message = ws.receive() ws.send(message) return all_urls = [ url('', Home), url('api', Api) ] options = {} # Template Engine searchpath = [''] engine = Engine( loader=FileLoader(searchpath), extensions=[ CoreExtension(), ]) engine.global_vars.update({ 'h': html_escape
""" """ from wheezy.routing import url from public.web.urls import error_urls from public.web.urls import public_urls from public.web.urls import static_urls from public.web.views import WelcomeHandler ## project from views.test import test from views.list import ListHandler all_urls = [ url('', WelcomeHandler, name='default'), url('', ListHandler, name='default'), url('add', ListHandler, name='list') ] all_urls += public_urls all_urls += [('error/', error_urls)] all_urls += static_urls # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2015 blackshirt __author__ = 'simbah' from wheezy.routing import url from wheezy.web.handlers import file_handler from views import IndexHandler from views import AddTrainingHandler, ListTrainingHandler all_urls = [ url('', IndexHandler, name='index'), url('add', AddTrainingHandler, name='add'), url('list', ListTrainingHandler, name='list'), url('static/{path:any}', file_handler(root='static/'), name='static'), url('favicon.ico', file_handler(root='/'), {'path': 'favicon.ico'}) ]
from wheezy.web.handlers import BaseHandler from wheezy.web.middleware import bootstrap_defaults from wheezy.web.middleware import path_routing_middleware_factory import ujson class WelcomeHandler(BaseHandler): def get(self): response = HTTPResponse(content_type="application/json; charset=UTF-8") response.write(ujson.dumps({"test": True})) return response all_urls = [ url("", WelcomeHandler, name="default"), # url('', welcome, name='welcome') ] options = {} main = WSGIApplication( middleware=[ bootstrap_defaults(url_mapping=all_urls), path_routing_middleware_factory, ], options=options, ) if __name__ == "__main__":
pq[:, :-needed] = q result = index.search(padded, pq, K=k, withDistance=True) ids = map(lambda x: pids[x], result[0][0].tolist()) return self.json_response({'ids': ids, 'dists': result[1][0].tolist()}) def welcome(request): response = HTTPResponse() response.write('Server is up!') return response all_urls = [ url('', welcome, name='default'), url('search', SearchHandler, name='search') ] options = {} web = WSGIApplication(middleware=[ bootstrap_defaults(url_mapping=all_urls), path_routing_middleware_factory ], options=options) indices = {} def load(entry, datafile): data = np.genfromtxt(datafile, delimiter=',') (m, n) = data.shape
from wheezy.http import HTTPResponse from wheezy.http import WSGIApplication from wheezy.routing import url from wheezy.web.handlers import BaseHandler from wheezy.web.middleware import bootstrap_defaults from wheezy.web.middleware import path_routing_middleware_factory import json class WelcomeHandler(BaseHandler): def get(self): response = HTTPResponse() quote = {'message': 'Hello, World!'} response.write(json.dumps(quote)) return response all_urls = [url('', WelcomeHandler, name='default')] options = {} main = WSGIApplication(middleware=[ bootstrap_defaults(url_mapping=all_urls), path_routing_middleware_factory ], options=options) if __name__ == '__main__': from wsgiref.simple_server import make_server try: make_server('', 8888, main).serve_forever() except KeyboardInterrupt: pass
""" """ from wheezy.routing import url from shared.views import url_index from membership.web.views import SignInHandler from membership.web.views import SignOutHandler from membership.web.views import SignUpHandler from membership.web.views import UserHandler membership_api_urls = [ url('signin', SignInHandler), url('signup', SignUpHandler), url('signout', SignOutHandler), url('user', UserHandler) ] membership_urls = [ url_index('signin', name='signin'), url_index('signup', name='signup') ]
credential.email = email_id if self.validate(credential, email_validator): room, created = get_or_create(EmailBase, email=email_id) if created: return self.json_response( {'success': "You are successfully added. We will invite on the beta launch"}) else: return self.json_response( {'success': "We will invite on the beta launch", 'error': "You are already registered."}) else: return self.json_response( {'error': "Wrong Email Address. Please Correct yourself."}) all_urls = [ url('', HomePage, name='default'), url('email', EmailPage, name='email'), url('static/{path:any}', file_handler(root='static/'), name='static') ] options = {} # Template Engine searchpath = [''] engine = Engine( loader=FileLoader(searchpath), extensions=[ CoreExtension(), WidgetExtension(),
response = HTTPResponse() response.headers = [(CONTENT_TYPE, CONTENT_TYPE_JSON)] response.write(response_db_write_queries()) return response class RequestCacheRead(BaseHandler): def get(self): response = HTTPResponse() response.headers = [(CONTENT_TYPE, CONTENT_TYPE_PLAIN)] response.write(response_cached()) return response all_urls = [ url('', RequestHtml, name='home'), url('1kb-response', Request1kb, name='1kbresponse'), url('100kb-response', Request100kb, name='100kbresponse'), url('1mb-response', Request1mb, name='1mbresponse'), url('json-response', RequestJson, name='jsonresponse'), url('html-response', RequestHtml, name='htmlresponse'), url('slow-response', RequestSlow, name='slowresponse'), url('db-read', RequestDBread, name='dbread'), url('db-write', RequestDBwrite, name='dbwrite'), url('/cache-read', RequestCacheRead, name='cacheread'), ] options = {} app = WSGIApplication( middleware=[ bootstrap_defaults(url_mapping=all_urls),
class MetricServer(DatabaseClass): SCHEMA = """ CREATE TABLE metric ( id SERIAL NOT NULL PRIMARY KEY, stage CHARACTER VARYING NOT NULL, metric CHARACTER VARYING NOT NULL, UNIQUE (stage, metric) ); CREATE TABLE metric_data ( metric_id INT NOT NULL, timestamp timestamp with time zone NOT NULL, value INT NOT NULL, CONSTRAINT metric_fk FOREIGN KEY (metric_id) REFERENCES metric (id) MATCH SIMPLE ); CREATE INDEX metric_id_idx ON metric_data (metric_id); CREATE INDEX timestamp_idx ON metric_data (timestamp ASC); """ URLS = [url("unshadow/metric/{any}", MetricHandler, name="Metrics")] _db = None def __init__(self, http_host, http_port, db_host, db_port, db_user, db_name, db_pass): self.http_host = http_host self.http_port = http_port self.db_host = db_host self.db_port = db_port self.db_user = db_user self.db_name = db_name self.db_pass = db_pass def start(self): """ Start service. """ self.setup_database('metric') # TODO use middleware instead. GLOBALS["db"] = self._db self.start_http_server() def setup_http_server(self): """ Configure and start the http server. """ self.start_http_server() def start_http_server(self): """ Start the HTTP server. """ self.wsgi_app = WSGIApplication(middleware=[ bootstrap_defaults(url_mapping=self.URLS), path_routing_middleware_factory ], options={}) socket_pair = (self.http_host, self.http_port) self.wsgi_server = make_server(self.http_host, self.http_port, self.wsgi_app) message = "HTTP Server running on http://{}:{}" logging.info(message.format(self.http_host, self.http_port)) self.wsgi_server.serve_forever()
fout.write(content) fout.close() response.write(conf.get('upload_url_prefix') + savefile) else: return bad_request() else: # bad request return bad_request() return response # url mapping all_urls = [ url('', ping, name='default'), url('upload', upload, name='upload') ] # for wsgi execute warnings.simplefilter('ignore') app = WSGIApplication(middleware=[ bootstrap_defaults(url_mapping=all_urls), path_routing_middleware_factory ], options={}) # for main execute if __name__ == '__main__': from wsgiref.handlers import BaseHandler from wsgiref.simple_server import make_server port = 8080