from time import time import logging python_path.insert( 0, path.abspath(path.join(path.dirname(__file__), path.pardir))) # pylint: disable=wrong-import-position from poorwsgi import Application, state # noqa from poorwsgi.response import EmptyResponse, redirect # noqa from poorwsgi.digest import check_digest, PasswordMap, hexdigest # noqa FILE = path.join(path.dirname(__file__), 'test.digest') logging.getLogger().setLevel("DEBUG") app = application = Application(__name__) # pylint: disable=invalid-name # application = app app.debug = True app.secret_key = sha256(str(time()).encode()).hexdigest() # app.auth_algorithm = 'SHA-256-sess' app.auth_type = 'Digest' app.auth_timeout = 60 ADMIN = 'Admin Zone' USER = '******' # user/looser, foo/bar, admin/admin, Ondřej/heslíčko app.auth_map = PasswordMap(FILE) app.auth_map.load() # pylint: disable=unused-argument
from poorwsgi import Application, state, request, uni, redirect from poorwsgi.session import PoorSession from sys import version_info import os if version_info[0] == 2 and version_info[1] < 7: from ordereddict import OrderedDict else: from collections import OrderedDict if version_info[0] >= 3: from io import FileIO file = FileIO app = Application() app.debug = True app.document_root = './' app.document_index = True app.secret_key = os.urandom(32) # random key each run class Storage(file): def __init__(self, directory, filename): self.path = directory + '/' + filename if os.access(self.path, os.F_OK): raise Exception("File %s exist yet" % filename) super(Storage, self).__init__(self.path, 'w+b')
string = self.receive_str() if string is None: raise WebSocketError("Socket was closed.") return string.encode('utf-8') obj = environment.get("wsgi.websocket") obj.receive_str = obj.receive obj.receive = MethodType(receive, obj) return environment.get("wsgi.websocket") logger = log.getLogger() logger.setLevel("DEBUG") poor = Application(__name__) poor.debug = True app = application = poor if uwsgi else WSocketApp(poor) @poor.route('/') def root(req): """Return Root (Index) page.""" ws_scheme = 'wss' if req.scheme == 'https' else 'ws' return """ <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title>WebSocket Example</title>
# pylint: disable=import-error, wrong-import-position from poorwsgi import Application, state, request, redirect # noqa from poorwsgi.session import PoorSession, SessionError # noqa from poorwsgi.response import Response, RedirectResponse, \ FileObjResponse, FileResponse, GeneratorResponse, \ EmptyResponse, HTTPException # noqa try: import uwsgi # type: ignore except ModuleNotFoundError: uwsgi = None # pylint: disable=invalid-name logger = log.getLogger() logger.setLevel("DEBUG") app = application = Application("simple") app.debug = True app.document_root = '.' app.document_index = True app.secret_key = os.urandom(32) # random key each run class MyValueError(ValueError): """My value error""" class Storage(file): def __init__(self, directory, filename): log.debug("directory: %s; filename: %s", directory, filename) self.path = directory + '/' + filename
import sys import logging as log EXAMPLES_PATH = os.path.dirname(__file__) sys.path.insert(0, os.path.abspath(os.path.join(EXAMPLES_PATH, os.path.pardir))) # pylint: disable=wrong-import-position from poorwsgi import Application, state # noqa from poorwsgi.request import FieldStorage # noqa from poorwsgi.response import HTTPException # noqa from poorwsgi.results import hbytes # noqa logger = log.getLogger() logger.setLevel("DEBUG") app = application = Application("large_file") app.debug = True app.auto_form = False # pylint: disable=consider-using-f-string class Blackhole: """Dummy File Object""" def __init__(self, filename): log.debug("Start uploading file: %s", filename) self.uploaded = 0 self.__hash = sha256() def write(self, data): """Only count uploaded data size."""
from poorwsgi import Application, state from docutils.core import publish_parts from docutils_tinyhtml import Writer from json import dumps from os import path from cStringIO import StringIO import re app = Application('docutils-editor') app.debug = True app.document_root = (path.abspath( path.join(path.dirname(__file__), path.pardir))) application = app # match for start of docutils system_message re_message = re.compile(r"[<>\w]+:(\d+): \((\w+)/(\d+)\) (.*)", re.U) def parse_system_messages(out): if not isinstance(out, str): out = out.decode() retval = set() for line in out.split('\n'): match = re_message.search(line) if match: retval.add(match.groups()) return tuple(retval)
"""Metrics example.""" from wsgiref.simple_server import make_server from time import time from sys import path as python_path import os EXAMPLES_PATH = os.path.dirname(__file__) python_path.insert( 0, os.path.abspath(os.path.join(EXAMPLES_PATH, os.path.pardir))) from poorwsgi import Application, state # noqa from poorwsgi.response import JSONResponse # noqa app = application = Application('metrics') class Metrics: """Simple metrics class.""" requests = 0 response_time = 0 best_time = float('inf') worst_time = 0 @staticmethod def avg(): """Return average response time.""" if Metrics.requests: return Metrics.response_time / Metrics.requests return 0
def app(): return Application(__name__)
from openapi_core.validation.exceptions import InvalidSecurity # type: ignore from openapi_core.templating.paths.exceptions import ( # type: ignore PathNotFound, OperationNotFound) TEST_PATH = path.dirname(__file__) python_path.insert(0, path.abspath(path.join(TEST_PATH, path.pardir))) from poorwsgi import Application, state # noqa from poorwsgi.response import Response, abort, HTTPException, \ JSONResponse # noqa from poorwsgi.openapi_wrapper import OpenAPIRequest, \ OpenAPIResponse # noqa from poorwsgi.session import PoorSession # noqa XXX = 'xxx' app = application = Application("OpenAPI3 Test App") app.debug = True app.secret_key = urandom(32) # random key each run request_validator = None response_validator = None options_headers = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Credentials": "true", "Access-Control-Allow-Methods": "GET, POST, OPTIONS", "Access-Control-Allow-Headers": "*", "Access-Control-Max-Age": "1728000", # 20 days "Content-Length": "0" }
EXAMPLES_PATH = os.path.dirname(__file__) python_path.insert( 0, os.path.abspath(os.path.join(EXAMPLES_PATH, os.path.pardir))) # pylint: disable=import-error, wrong-import-position from poorwsgi import Application, state # noqa from poorwsgi.response import JSONResponse, JSONGeneratorResponse # noqa from poorwsgi.request import parse_json_request # noqa try: import uwsgi # type: ignore except ModuleNotFoundError: uwsgi = None # pylint: disable=invalid-name app = application = Application("JSON") app.debug = True @app.route('/test/json', method=state.METHOD_GET_POST) def test_json(req): """Test GET / POST json""" # numbers are complete list data = req.json if req.is_chunked_request: raw = b'' # chunk must be read with extra method, uwsgi has own chunk = uwsgi.chunked_read() if uwsgi else req.read_chunk() while chunk: raw += chunk chunk = uwsgi.chunked_read() if uwsgi else req.read_chunk()
from poorwsgi import Application, state from docutils.core import publish_parts from docutils_tinyhtml import Writer from json import dumps from os import path from cStringIO import StringIO import re app = Application('docutils-editor') app.debug = True app.document_root = (path.abspath(path.join(path.dirname(__file__), path.pardir))) application = app # match for start of docutils system_message re_message = re.compile(r"[<>\w]+:(\d+): \((\w+)/(\d+)\) (.*)", re.U) def parse_system_messages(out): if not isinstance(out, str): out = out.decode() retval = set() for line in out.split('\n'): match = re_message.search(line) if match: retval.add(match.groups()) return tuple(retval)
"""Test of csrf-protect library. This test use `PoorWSGI <http://poorhttp.zeropage.cz/poorwsgi.html>` WSGI middleware. But library could be use with anyone. """ from poorwsgi import Application, redirect, SERVER_RETURN, state from poorwsgi.session import PoorSession from wsgiref.simple_server import make_server from inspect import cleandoc from csrf import random_string, get_token, check_token app = Application('test') app.debug = True secret = random_string(length=32) def create_referer(req, referer): return "%s://%s%s" % (req.scheme, req.hostname, referer) @app.route('/login') def login(req): # password check is missing ! cookie = PoorSession(req) cookie.data['hash'] = random_string() # cookie data are crypted with poorwsgi secret key cookie.header(req, req.headers_out) redirect(req, '/')