def get(self, endpoint=None): request = Request() url = self.auth_url if endpoint: url = "{}/{}".format(self.auth_url, endpoint) print url return request.get(url)
def test_headers(self): request = Request('GET', 'http', {'Connection': 'keep-alive'}) self.assertIsInstance(request.headers, Headers) headers = Headers({'Connection': 'keep-alive'}) request = Request('GET', 'http', headers) self.assertTrue(request) self.assertEqual(request.header('connection'), 'keep-alive')
def test_headers(self): request = Request("GET", "http", {"Connection": "keep-alive"}) self.assertIsInstance(request.headers, Headers) headers = Headers({"Connection": "keep-alive"}) request = Request("GET", "http", headers) self.assertTrue(request) self.assertEqual(request.header("connection"), "keep-alive")
def test_method(self): for method in ["GET", "get", "gEt"]: request = Request(method, "http") self.assertEqual(request.method, method) request = Request("GET", "http") request.method = "POST" self.assertEqual(request.method, "POST") request.method = "post" self.assertEqual(request.method, "post")
def _test_request(self, method): client = HTTPClient() client.add_handler('request_send', _test_cb) request = Request(method, tests[method]['url'], tests[method]['headers']) if 'content' in tests[method]: request.content = tests[method]['content'] resp = client.request(request) self.assertTrue(resp) self.assertEqual(resp.status, 204)
def test_overwrite_handlers(self): request = Request('GET', 'http') handlers = Handlers() handlers.add_handler('request_send', lambda r: 1) resp = handlers.dispatch('request_send', request) self.assertEqual(resp, 1) handlers.add_handler('request_send', lambda r: 2) resp = handlers.dispatch('request_send', request) self.assertEqual(resp, 2)
def get_user(self, username): endpoint = Url(self.base_url) endpoint.path.append('users') endpoint.path.append(username) request = Request('GET', endpoint) response = self.user_agent.request(request) if response.is_success: return json.loads(response.content) else: raise Exception(response.status_line)
def mirror(self, url, filename): req = Request('GET', url) res = self.request(req) if res.is_success: f = open(filename, 'w') f.write(res.content) f.close() last_modified = Date.time2epoch(res.last_modified) if last_modified: os.utime(file, (last_modified, last_modified))
def main(): # Testing HTTP/1.1 client = socket(AF_INET, SOCK_STREAM) client.connect(ADDR) # client.send('GET / HTTP/1.1\r\n\r\n') data = client.recv(BUFF_SIZE) print(':'.join(x.encode('hex') for x in data)) # send preface client.send('\x50\x52\x49\x20\x2a\x20\x48\x54\x54\x50\x2f\x32\x2e\x30\x0d\x0a\x0d\x0a\x53\x4d\x0d\x0a\x0d\x0a') client.send('\x00\x00\x00\x04\x00\x00\x00\x00\x00') # Setting Frame data = client.recv(BUFF_SIZE) print(':'.join(x.encode('hex') for x in data)) stream = Stream() request = Request() request.status = Status() request.status.path = '/' request.status.method = 'GET' request.headers = {} # request.headers['date'] = Header('Date', 'Sun, 06 Nov 2015 08:49:37 GMT') msg = stream.send_http_msg(request) print(':'.join(hex(x) for x in msg)) client.send(msg) data = client.recv(BUFF_SIZE) print(':'.join(x.encode('hex') for x in data)) client.send('\x00\x00\x00\x04\x01\x00\x00\x00\x00') # Setting Frame data = client.recv(BUFF_SIZE) print(':'.join(x.encode('hex') for x in data))
def _follow_redirect(self, resp, r): redirects = list() while (resp.is_redirect and len(redirects) < self.max_redirect): location = resp.header('location') if location is None: break redirects.append(resp) req = Request(r.method, location) resp = self._make_request(req) location = resp.header('location') resp.redirects = redirects return resp
def generateRequest(method, uri, generalHeaderDict, requestHeaderDict, entityHeaderDict, entity, http_version='HTTP/1.1'): http_request = Request() http_request.set_method(method) http_request.set_uri(uri) http_request.set_entity(entity) http_request.generalHeader.set_value( {'Datetime': datetime.now().strftime('%Y-%m-%d %H:%M:%S')}) http_request.requestHeader.set_value(requestHeaderDict) entityHeaderDict['Content_Length'] = str(len(entity)) http_request.entityHeader.set_value(entityHeaderDict) return http_request
def test_method(self): for method in ['GET', 'get', 'gEt']: request = Request(method, 'http') self.assertEqual(request.method, method) request = Request('GET', 'http') request.method = 'POST' self.assertEqual(request.method, 'POST') request.method = 'post' self.assertEqual(request.method, 'post')
def test_prepare(self): request = Request('FOO', 'http') client = HTTPClient() client.add_handler('request_prepare', _cb_request_prepare) resp = client.request(request) self.assertEqual(resp.status, 400) handlers = Handlers() handlers.add_handler('request_prepare', _cb_request_prepare_change_request) req = handlers.dispatch('request_prepare', request) self.assertEqual(req.method, 'PUT') handlers = Handlers() handlers.add_handler('request_prepare', _cb_request_prepare_do_nothing) req = handlers.dispatch('request_prepare', request) self.assertEqual(req.method, 'FOO') self.assertEqual(req.url, 'http')
def test_base_url(self): response = Response(status=200, message='OK', headers={'Content-Base': 'http://foo'}) self.assertEqual(response.base, 'http://foo/') self.assertIsInstance(response.base, Url) response = Response(status=200, message='OK', headers={'Content-Location': 'http://bar'}) self.assertEqual(response.base, 'http://bar/') self.assertIsInstance(response.base, Url) request = Request('GET', 'http://baz') response = Response(status=200, message='OK', request=request) self.assertEqual(response.base, 'http://baz/') self.assertIsInstance(response.base, Url) response = Response(status=200) self.assertEqual(response.base, None)
def test_base(self): request = Request('GET', 'http://github.com') self.assertTrue(request) self.assertEqual(request.method, 'GET')
def _wsgi(environ, start_response): """A application for WSGI server.""" global g g.request = Request(environ) g.response = Response() path_info = g.request.path_info # deal with normal page try: return self._handle_response(path_info, start_response) # deal with redirection except RedirectError as e: if e.location == 'login_url': if hasattr(self, '_login_url'): url = self._login_url else: logging.warning('-- You should set `login_url` in \ settings dict.') raise HttpError(404) else: url = e.location g.response.status = e.status #g.response.location = 'http://' + g.request.host + url return self._handle_response(url, start_response) # deal with bad request except HttpError as e: if hasattr(self, '_not_found_page'): url = self._not_found_page g.response.status = e.status return self._handle_response(url, start_response) else: # add all urls later. data = """<html> <head> <title>404</title> <style type="text/css"> body { margin: 0 auto; width: 50%; font-family: "Hiragino Sans GB", "Microsoft YaHei","WenQuanYi Micro Hei", sans-serif; } .bd { margin: 10% auto; border: 1px solid #696969; background: #696969; border-radius: 5px; } p { color: #fff; font-size: 43px; font-weight: bold; text-align: center; text-shadow: 0 0 5px #fefcc9, 3px -3px 5px #feec85, -5px -5px 10px #ffae34, 5px -10px 13px #ec760c, -5px -15px 15px #cd4606, 0 -20px 18px #973716, 3px -23px 20px #451b0e; } </style> </head> <body> <div class="bd"> <p>Oh, God! The page Not Found!</p> </div> </body> </html> """ start_response(e.status, g.response.headers) return [data] finally: del g.request del g.response
def head(url): req = Request('HEAD', url) result = client().request(req) if result.is_success: return result return None
def test_request(self): request = Request('GET', 'http://foobar') response = Response(status=200, message='OK', headers={}, request=request)
def put(self, endpoint, data): request = Request() url = "{}/{}".format(self.auth_url, endpoint) print url request.put(url, data)
#!/usr/bin/env python # -*- coding: utf-8 -*- from http import BaseView, Request import random class OmikujiView(BaseView): sushi_list = ['はまち', 'まぐろ', 'さば', 'さーもん', 'いくら', 'ほたて', 'たい', 'えび', 'たこ', 'いくら'] def get(self, request): sushi = random.choice((self.sushi_list)) content = "<h1>すしランダム</h1><p>つ「%s」</p>" % sushi return self.generate_response(content) if __name__ == "__main__": req = Request() print(OmikujiView().render(req))
def handleRequest(raw_request): http_request = Request() http_request.unpack(raw_request) return http_request
def get(self, url, headers={}): request = Request('GET', url, headers=headers) return self._request(request)
def head(self, url, headers={}): request = Request('HEAD', url, headers=headers) return self._request(request)
def test_execute_handler(self): request = Request('GET', 'http') handlers = Handlers() handlers.add_handler('request_send', _cb_request_send) resp = handlers.dispatch('request_send', request) self.assertIsInstance(resp, Response)
def delete(self, url, headers={}, content=None): request = Request('DELETE', url, headers=headers) return self._request(request)
import sys sys.path.append('.') from datetime import datetime from http import Client, Request, Date client = Client(agent='my uber agent') request = Request('HEAD', 'http://lumberjaph.net') request.if_modified_since = datetime(2011, 12, 1, 0, 0) response = client.request(request) if response.is_success: print "yeah, success!" print "status: {status}".format(status=response.status) print "message: {message}".format(message=response.message) print "content length: {length}".format(length=response.content_length) print "last modified in epoch: {last_modified}".format(last_modified=Date.time2epoch(response.last_modified)) print "last modified in string: {last_modified}".format(last_modified=response.header('Last-Modified')) if response.content_is_text: print response.content else: print "oups! {status_line}".format(status_line=response.status_line)
import sys sys.path.append('.') from httpclient. async import HTTPClientAsync from http import Request ua = HTTPClientAsync() req = Request('GET', 'http://proximobus.appspot.com/agencies.json') res = ua.request(req) if res.is_success: print res.content #try: #req = Request('GET', 'http://some.bad.address.that.does.not.exist/') #res = ua.request(req) #except Exception, e: #print "OK" ##print e ##print res.is_error
def test_date_headers(self): request = Request('GET', 'http') request.if_modified_since = datetime(2011, 12, 12, 12, 0, 0) self.assertEqual(request._headers.get('If-Modified-Since'), 'Mon, 12 Dec 2011 12:00:00 GMT')
def fetcher(self): url = self.creq.get() response = Request(url, self.timeout) self.cres.put(response) self.pool.spawn_n(self.parse_coroutine) logger.info('Fetched: %s (%s)' % (url, response.status))
def post(self, url, headers={}, content=None): request = Request('POST', url, headers=headers, content=content) return self._request(request)
def test_content(self): request = Request('GET', 'http', content='foo') self.assertEqual(request.content, 'foo')
def _cb_request_prepare_change_request(request): request = Request('PUT', 'http') return request
import functools import mimetypes from json import dumps from urlparse import urljoin from traceback import format_exc from types import StringType from config import HTTP_CODES, DEBUG from http import Request, Response from exception import HTTPError, HTTPResponse from router import Router from util import depr, yieldroutes, toa, parse_date, _reloader_child, _reloader_observer from util import WSGIFileWrapper from server import ServerAdapter, WSGIRefServer request = Request() response = Response() class Brick(object): def __init__(self, catchall=True, autojson=True, config=None): self.routes = Router() self._logger = None self.mounts = {} self.error_handler = {} self.catchall = catchall self.config = config or {} self.serve = True self.castfilter = [] if autojson and dumps: self.add_filter(dict, dumps)
import sys sys.path.append('.') from datetime import datetime from http import Client, Request, Date client = Client(agent='my uber agent') request = Request('HEAD', 'http://lumberjaph.net') request.if_modified_since = datetime(2011, 12, 1, 0, 0) response = client.request(request) if response.is_success: print "yeah, success!" print "status: {status}".format(status=response.status) print "message: {message}".format(message=response.message) print "content length: {length}".format(length=response.content_length) print "last modified in epoch: {last_modified}".format( last_modified=Date.time2epoch(response.last_modified)) print "last modified in string: {last_modified}".format( last_modified=response.header('Last-Modified')) if response.content_is_text: print response.content else: print "oups! {status_line}".format(status_line=response.status_line)
def test_url(self): request = Request('GET', 'http') self.assertIsInstance(request.url, Url)
def test_header(self): request = Request("GET", "http://lumberjaph.net") request.header("If-Modified-Since", "Wed, 08 Feb 2012 05:08:50 GMT") self.assertEqual(request.header("If-Modified-Since"), "Wed, 08 Feb 2012 05:08:50 GMT")
def test_date_headers(self): request = Request("GET", "http") request.if_modified_since = datetime(2011, 12, 12, 12, 0, 0) self.assertEqual(request._headers.get("If-Modified-Since"), "Mon, 12 Dec 2011 12:00:00 GMT")
def test_response(self): request = Request('GET', 'http') client = HTTPClient() client.add_handler('request_send', _cb_request_send) #client.add_handler('response_done', _cb_response_done) resp = client.request(request)