def __init__(self, **kwargs): self.server = Webserver() super().__init__(**kwargs) # add middlewares and other apps here... self.server.add_app(StaticApp(prefix='static', path='static')) self.server.add_app(self)
def __init__(self, **kwargs): self.server = Webserver() super().__init__(**kwargs) static_prefix = kwargs.get('static_prefix', 'static') static_path = kwargs.get('static_path', 'static') # add middlewares and other apps here... self.server.add_app(StaticApp(prefix=static_prefix, path=static_path)) self.server.add_app(self)
class MicroApp(App): """Puts a micro framework (see flask, sinatra etc.) on top of the Webserver framework. Usage: app = MicroApp() @app.get('') def index(request, response, pathmatch): response.send(body="Hey!") @app.put('thing/(?P<thing_id>)') def update_thing(request, response, pathmatch): thing = model.find_thing(pathmatch.group('thing_id')) thing.foo = request.params['foo'] thing.store() response.send_redirect('/') @app.route('info') def info(request, response, pathmatch): response.send(body="Just for info") @app.route('info', methods=['PUT', 'POST']) def info(request, response, pathmatch): response.send(body="Just for info") """ def __init__(self, **kwargs): self.server = Webserver() super().__init__(**kwargs) # add middlewares and other apps here... self.server.add_app(StaticApp(prefix='static', path='static')) self.server.add_app(self) def get(self, url): """Decorator function for GET routes that maps to the route method.""" return self.route(url, ['GET']) def post(self, url): """Decorator function for GET routes that maps to the route method.""" return self.route(url, ['POST']) def put(self, url): """Decorator function for GET routes that maps to the route method.""" return self.route(url, ['PUT']) def delete(self, url): """Decorator function for GET routes that maps to the route method.""" return self.route(url, ['DELETE']) def route(self, url, methods=None): """Decorator function with arguments. Returns a decorator function that takes a function and wraps it or has some side effetcs (like registering the route).""" def wrap(f): self.add_route(url, f, methods=methods) return f return wrap def serve(self): self.server.serve()
request.params['_username'])) else: return response.send_template( 'login.tmpl', {'message': 'Wrong username or password. Try again.'}) # send login form return response.send_template( 'login.tmpl', {'user': server.usermodel.AnonymousUser()}) if __name__ == '__main__': db = sqlite.connect('minitwitter.sqlite') # use sqlite db db.row_factory = sqlite.Row # fetch rows as Row objects (easier to access) s = Webserver() s.set_templating("jinja2") s.set_templating_path("templates.jinja2") s.add_middleware(SessionMiddleware()) s.add_middleware(CsrfMiddleware()) s.add_app(UsermanagementApp(db_connection=db) ) # Sub-App: create, change, delete users. (code in server/apps) s.add_app(StaticApp(prefix='static', path='static')) # deliver static files s.add_app(MiniTwitterApp('data', db_connection=db)) # the twitter app log(0, "Server running.") s.serve()
from server.webserver import Webserver, App class DummyApp(App): """A very silly simple App.""" def register_routes(self): self.add_route("", self.dummy) def dummy(self, request, response, pathmatch): response.send(200, body="Huhuh, ich bin ein dummy.") server = Webserver(8080) # Initialize webserver on port 8080 server.add_app(DummyApp()) # register DummyApp without prefix server.serve() # listen for connections and serve
if '_username' in request.params and '_password' in request.params: users = server.usermodel.Users(self.db_connection) user = users.login(request.params['_username'], request.params['_password']) if user: request.session['user'] = user # save user to session return response.send_redirect("/?message=Successfully logged in as <i>{}</i>.".format(request.params['_username'])) else: return response.send_template('login.tmpl',{'message':'Wrong username or password. Try again.'}) # send login form return response.send_template('login.tmpl',{}) if __name__ == '__main__': db = sqlite.connect('minitwitter.sqlite') db.row_factory = sqlite.Row s = Webserver() s.set_templating("pystache") s.set_templating_path("templates.mustache") s.add_middleware(SessionMiddleware()) s.add_app(UsermanagementApp(db_connection=db)) s.add_app(StaticApp(prefix='static', path='static')) s.add_app(MiniTwitterApp('data', db_connection=db)) log(0, "Server running.") s.serve()
for (url, values) in hitlist: msg += """<h3><a href="{link}">{title}</a></h3> <p><a href="{link}">{link}</a></p> <p>{teaser}<p>""".format( link=url, title=self.store.pages[url]['title'], teaser=self.store.get_teaser(url, q)) response.send_template('templates/search/search.tmpl', { 'q': q, 'netloc': self.store.netloc, 'msg': msg }) if __name__ == '__main__': # entry = 'https://www.informatik.uni-osnabrueck.de' # entry = 'https://www.uni-osnabrueck.de' # entry = 'https://www.virtuos.uni-osnabrueck.de' entry = 'http://vm009.rz.uos.de' s = load_store(entry) if not s: s = Store(entry) c = Crawler(s) c.crawl() s.save() w = Webserver() w.add_app(SearchApp(s, prefix='')) w.serve() webbrowser.open_new_tab("http://localhost:8080/")
'icon': '☂', 'name': 'Walter Sparbier' } }) def page3(self, request, response, pathmatch): """The third page.""" response.send_template( 'page3.tmpl', { 'title': 'Page 3', 'page3': True, 'magic_numbers': [7, 13, 23, 27, 42], 'current_user': { 'id': 815, 'icon': '☘', 'name': 'Tobias Findeisen' }, 'message': "<i>HTML-Content ☃</i>" }) if __name__ == '__main__': s = Webserver() s.set_templating("pystache") s.set_templating_path("templates.mustache/skel") s.add_app(SkelApp()) s.add_app(StaticApp(prefix='static', path='static')) s.serve()
class SQLInjectionApp(App): """App vulnerable to path traversal attacks. Should deliver files from the data directory but can easily be abused to deliver any file that current process can read.""" def register_routes(self): self.add_route("", self.show_form) self.add_route("data", self.show_data) def show_form(self, request, response, pathmatch): response.send(body=""" <!DOCTYPE html> <html> <body> <form action='/data' method=get> <input type=text name=data> </form> </body> </html>""") def show_data(self, request, response, pathmatch): persons = Person.find(lastname=request.params['data']) response.send(body="<br>".join([p.__str__() for p in persons])) if __name__ == '__main__': db_setup() s = Webserver() s.add_app(SQLInjectionApp()) s.serve()
except (ValueError, TypeError): result1 = "Bitte einen gültigen Suchbegriff eingeben" if not hasattr(self, "s"): self.s = Store(netloc="http://vm009.rz.uos.de") if not hasattr(self, "c"): self.c = Crawler(self.s) if self.s.empty(): try: self.s.load() except: self.c.crawl() results = self.s.search(search_term.split()) results.extend(["", "", ""]) print(results) result1, result2, result3 = results[0:3] response.send_template('templates/search_engine/search.tmpl', { 'result1': result1, 'result2': result2, 'result3': result3 }) if __name__ == '__main__': print("check1") s = Webserver(8040) s.add_app(SearchEngine(prefix='')) s.serve() webbrowser.open_new_tab("http://localhost:8020/")
newmsg = '' (found, msg) = g.guess(guess) if found: # destroy session # new session and number will be generated next time request.session.renew() count = 1 else: # pass sessid id to hidden input field count = g.count + 1 d = {'msg': msg, 'newmsg': newmsg, 'cnt': count, 'variant': 'Session per Cookie', 'hidden': ''} response.send_template('show.tmpl', d) if __name__ == '__main__': s = Webserver() s.set_templating("jinja2") s.set_templating_path("templates.jinja2") s.add_app(WelcomeApp()) s.add_app(GlobalGuessApp(prefix='global/?')) s.add_app(CookieGuesserApp(prefix='cookies/?')) s.add_app(GetGuesserApp(prefix='get/?')) s.add_app(SessionGuesserApp(prefix='session/?')) s.add_app(StaticApp(prefix='', path='static')) s.add_middleware(SessionMiddleware()) # let's have sessions s.serve()
response.send(body=""" <!DOCTYPE html> <html> <body> <form action='/data' method=get> <input type=text name=data> </form> </body> </html>""") def show_data(self, request, response, pathmatch): filename = request.params['data'] import re if not re.match(r"[a-zA-Z0-9_-]+", filename): raise StopProcessing(400, "Invalid data parameter.") import os.path datapath = os.path.abspath("data") path = os.path.abspath("data/" + filename) if not path.startswith(datapath): raise StopProcessing(400, "Directory Traversal attack.") with open(path, "r") as f: response.send(body=f.read()) if __name__ == '__main__': s = Webserver() s.add_app(PathTraversalApp()) s.serve()
])) response.set_content_type("text/html") response.send(body=body) class FortyTwoApp(App): """A very wise simple App.""" def register_routes(self): self.add_route("", self.theanswer) def theanswer(self, request, response, pathmatch): response.send(200, body="<html><body><h1>42</h1></body></html>") if __name__ == '__main__': s = Webserver() # Static app for static folder static = StaticApp(prefix='static', path='static', name='Statischer Dateibereich') static.default_entry = "/static/" s.add_app(static) # Flappy Bird clone via StaticApp floppy = StaticApp(prefix='floppy', path='3rdparty/floppybird', name='Floppy Bird (js game)') floppy.default_entry = "/floppy/index.html" s.add_app(floppy)
'current_user': { 'id': 815, 'icon': '☘', 'name': 'Tobias Findeisen' } }) def page3(self, request, response, pathmatch): """The third page.""" response.send_template( 'page3.tmpl', { 'magic_numbers': [7, 13, 23, 27, 42], 'current_user': { 'id': 815, 'icon': '☘', 'name': 'Tobias Findeisen' }, 'message': "<i>HTML-Content ☃</i>" }) if __name__ == '__main__': s = Webserver() s.set_templating("jinja2") s.set_templating_path("templates.jinja2/skel") s.add_app(SkelApp()) s.add_app(StaticApp(prefix='static', path='static')) s.serve()
class CelsiusApp(App): """ Webanwendung zum Konvertieren von Celisus-Grad in Fahrenheit-Grad. Diese sehr einfache Anwendung demonstriert die Verwendung des Server-Frameworks. Die Klasse Celsius-App benötigt zwei Methoden: 1. Registrierung der Routen 2. Definition eines Request-Handlers """ def register_routes(self): self.add_route('', self.celsius) # there is only one route for everything def celsius(self, request, response, pathmatch=None): msg = "" if 'celsius' in request.params: # check if parameter is given try: # calculate fahrenheit = float(request.params['celsius']) * 9 / 5 + 32 msg = "{}° Celsius sind {:4.2f}° Fahrenheit".format( request.params['celsius'], fahrenheit) except (ValueError, TypeError): msg = "Bitte eine Zahl eingeben." response.send_template('templates/celsius/celsius.tmpl', {'msg': msg}) if __name__ == '__main__': s = Webserver() s.add_app(CelsiusApp(prefix='celsius')) s.serve() webbrowser.open_new_tab("http://localhost:8080/celsius")