def test_sessions(): a = Malt() @a.get('/') def dump_session(request): old_sess = dict(request.session) request.session['a'] = 2 return jsonify(old_sess) wsgi = a.wsgi_app({'SESSIONS': True, 'SECRET_KEY': 'abc'}) # Capture response headers headers = [None] def start_response(_, h): headers[0] = h # Send with a valid session session_token = 'eyJhIjoxfQ.2XFQKMS-erhoKkSGsezDxFsim6YctUnzxaiiMP1wzFs' environ = { 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/', 'HTTP_COOKIE': 'session=' + session_token, } rv = wsgi(environ, start_response) rv_text = next(iter(rv)).decode('utf-8') assert json.loads(rv_text) == {'a': 1} # Check response session cookie set_cookie = next(v for k, v in headers[0] if k.lower() == 'set-cookie') expected = 'eyJhIjoyfQ.WW2DtOr1pkaM9nrC9sw2kHW3Cxd57hDhLie--g46DjE' assert set_cookie == 'session=' + expected
def test_config(): a = Malt() @a.get('/') def dump_config(request): return jsonify(request.config) wsgi = a.wsgi_app({'a': 'b'}) environ = { 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/', } rv = wsgi(environ, lambda status, headers: None) rv_text = next(iter(rv)).decode('utf-8') assert json.loads(rv_text)['a'] == 'b'
@app.get('^/get$') def get(request): return json({ 'args': {}, 'headers': headers_dict(request.headers), 'origin': request.remote_addr, 'url': request.url, }, pretty=True) @app.post('^/post$') def post(request): return json({ 'args': {}, 'data': request.data(), 'headers': headers_dict(request.headers), 'origin': request.remote_addr, 'url': request.url, }, pretty=True) wsgi = app.wsgi_app({}) if __name__ == '__main__': server = make_server('localhost', 5000, wsgi) print('Running locally on http://localhost:5000') server.serve_forever()
@app.post('^/tasks$') def create_task(request): data = request.json() try: name = data['name'] except (KeyError, TypeError): raise HTTPException(400, 'Missing task name') task = {'id': len(tasks), 'name': name} tasks.append(task) return Response('/tasks/{0:d}'.format(task['id'])) @app.get('^/tasks/(\d+)$') def get_task(request, task_id): task_id = int(task_id) try: task = tasks[task_id] except IndexError: raise HTTPException(404) return json({'task': task}) wsgi = app.wsgi_app({}) server = make_server('localhost', 5000, wsgi) print('Running locally on http://localhost:5000') server.serve_forever()