def test_submountedRoute(self): """ L{Klein.subroute} adds functions as routable endpoints. """ app = Klein() with app.subroute("/sub") as app: @app.route("/prefixed_uri") def foo_endpoint(request): return b"foo" c = app.url_map.bind("sub/prefixed_uri") self.assertEqual(c.match("/sub/prefixed_uri"), ("foo_endpoint", {})) self.assertEqual(len(app.endpoints), 1) self.assertEqual(app.execute_endpoint("foo_endpoint", DummyRequest(1)), b"foo")
def test_submountedRoute(self): """ L{Klein.subroute} adds functions as routable endpoints. """ app = Klein() with app.subroute("/sub") as app: @app.route("/prefixed_uri") def foo_endpoint(request): return b"foo" c = app.url_map.bind("sub/prefixed_uri") self.assertEqual( c.match("/sub/prefixed_uri"), ("foo_endpoint", {})) self.assertEqual( len(app.endpoints), 1) self.assertEqual( app.execute_endpoint("foo_endpoint", DummyRequest(1)), b"foo")
self.items.append(item) def return_items(self, result): return self.items def return_spider_output(output): """ :param output: items scraped by CrawlerRunner :return: json with list of items """ # this just turns items into dictionaries # you may want to use Scrapy JSON serializer here return json.dumps([dict(item) for item in output], ensure_ascii=False) with app.subroute("/api/v1") as app: @app.route("/crawl") def schedule(request): print(1) urls = [ # "https://tech.meituan.com/2020/08/13/openstack-to-kubernetes-in-meituan.html" "https://tech.meituan.com/2013/12/04/yui3-practice.html" ] runner = MyCrawlerRunner(settings=get_project_settings()) spider = MeituanArticleSpider deferred = runner.crawl(spider, urls=urls) # deferred.addCallback(return_spider_output) return deferred
from klein import Klein app = Klein() @app.route('/hello') def index(request): return 'Hello from the subroutes example' with app.subroute('/blue') as sub: @sub.route('/first') def first(request): return 'first' @sub.route('/second') def second(request): return 'second' @sub.route('/third') def third(request): return 'third'
from klein import Klein from api.policy import route as policy_route from api.object import route as object_route app = Klein() with app.subroute("/api") as app: policy_route(app) object_route(app)
pass def get_file_info(uuid): with open(LINKS) as f: for line in f: uuid_, path, expire = [x.strip() for x in line.split(',')] if uuid_ == uuid: expire = parse_date(expire) return path, expire raise Fail('uuid not found') app = Klein() with app.subroute(BASEURL) as app: @app.route('/<uuid>/<filename>', methods=['GET', 'HEAD']) def serve_files(request, uuid, filename): UUID(uuid) # just create it to see if it validates path, expiry_date = get_file_info(uuid) if datetime.now(timezone.utc) > expiry_date: raise Fail('expired') if filename != os.path.basename(path): raise Fail('path does not match') return File(os.path.join(BASEDIR, path)) @app.route('/<uuid>/<filename>/', methods=['GET', 'HEAD'], branch=True) def serve_dir(request, uuid, filename): return serve_files(request, uuid, filename) @app.handle_errors
from hashlib import md5 from io import BytesIO from time import sleep from klein import Klein from twisted.web.client import getPage from twisted.internet import defer, threads, reactor app = Klein() D = defer.Deferred() #---------- Routes ----------# with app.subroute('/async') as sub: @sub.route('/simple') def simple(request): """ Create a callback chain that will underline and italicise some text. """ global D D = defer.Deferred() D.addCallback(addTag, 'i') # italics D.addCallback(addTag, 'u') # underline return D @sub.route('/simple/fire') def startSimpleChain(request): """ Start the callback chain, if it hasn't started already. """
if getattr(sys, 'frozen', False): # By default py2exe tries to write log to dirname(sys.executable) which fails when installed import tempfile sys.stdout = sys.stderr = open(join(tempfile.gettempdir(), '%s.log' % appname), 'wt', 0) # unbuffered print '%s %s %s' % (applongname, appversion, strftime('%Y-%m-%dT%H:%M:%S', localtime())) root = tk.Tk() app = AppWindow(root) # Create desired endpoint endpoint_description = "tcp:port=8080:interface=127.0.0.1" endpoint = endpoints.serverFromString(reactor, endpoint_description) # add oauth2 subpath to webserver with webapp.subroute("/oauth2"): oauth2_webapp(webapp) # This actually starts listening on the endpoint with the Klein app endpoint.listen(Site(webapp.resource())) # add gui (tkinter) to twisted reactor tksupport.install(root) # After doing other things like setting up logging, # starting other services in the reactor or # listening on other ports or sockets: reactor.run() # root.mainloop()
import json from twisted.internet.defer import inlineCallbacks, returnValue from klein import Klein from blockstore_client import config, client app = Klein() conf = config.get_config() conf["network"] = "mainnet" proxy = client.session(conf, conf['server'], conf['port']) with app.subroute("/") as app: @app.route('/') def pg_root(request): request.setHeader('Content-Type', 'application/json') responsebody = {'msg': 'this is root'} return json.dumps(responsebody) @app.route('/about') def pg_about(request): request.setHeader('Content-Type', 'application/json') responsebody = {'msg': 'this is about'} return json.dumps(responsebody) with app.subroute('/api'): with app.subroute('/v1'): # Returns server status # http://<url>/api/<version>/status
def render_without_request(template_name, **template_vars): """ Usage is the same as flask.render_template: render_without_request('my_template.html', var1='foo', var2='bar') """ env = jinja2.Environment(loader=jinja2.PackageLoader('rest', 'templates')) template = env.get_template(template_name) return template.render(**template_vars) ''' Sub routes pertaining to polisd actions ''' with app.subroute("/daemon") as daemon: ''' startpolis Serves a page with all mns and possibility to restart one by selecting When given masternodes mns=[indexes,..] and params it will try to execute: polisd params on each. if no params it'll just use default --daemon (not necessary) ''' @daemon.route('/startpolis', methods=['GET', 'POST']) def start_polisd(request): if request.method == 'POST': mns = request.form.getlist('mns') actions = request.form.getlist('params') result = 'Attempted starting: ' + ', '.join(mns)