Ejemplo n.º 1
0
 def prepare_response(self, content, status_code, content_type, headers):
     response = HTTPResponse(content_type=content_type)
     response.write(content)
     response.status_code = status_code
     for name, value in headers.iteritems():
         response.headers.append((name, value))
     return response
Ejemplo n.º 2
0
def simple_template_response(template, extra_data=None):

    extra_data = extra_data or {}
    template_handler = get_template_handler()
    response = HTTPResponse()
    response.write(template_handler(template, extra_data))
    return response
Ejemplo n.º 3
0
def upload(request):
    #print 'form:', request.form
    #print 'uploaded:', request.files

    response = HTTPResponse()
    # check data integrity:
    if request.files.get('data') and request.form.get('crc'):

        storage = request.files.get('data')[0] # raw object
        crc = request.form.get('crc')[0] # crc for compressed content

        if str(zlib.crc32(storage.value)) == crc: # check integrity
            # return file save result
            content = zlib.decompress(storage.value)
            # write to file here
            savefile = storage.filename if storage.filename else (datetime.now().strftime('%Y%m%d%H%M%S') + str(random.randint(0,100)) + '.html')
            fout = open(os.path.join(conf.get('upload_dir'), savefile), 'w')
            fout.write(content)
            fout.close()

            response.write(conf.get('upload_url_prefix') + savefile)
        else:
            return bad_request()
    else:
        # bad request
        return bad_request()
            
    return response
Ejemplo n.º 4
0
def upload(request):
    #print 'form:', request.form
    #print 'uploaded:', request.files

    response = HTTPResponse()
    # check data integrity:
    if request.files.get('data') and request.form.get('crc'):

        storage = request.files.get('data')[0]  # raw object
        crc = request.form.get('crc')[0]  # crc for compressed content

        if str(zlib.crc32(storage.value)) == crc:  # check integrity
            # return file save result
            content = zlib.decompress(storage.value)
            # write to file here
            savefile = storage.filename if storage.filename else (
                datetime.now().strftime('%Y%m%d%H%M%S') +
                str(random.randint(0, 100)) + '.html')
            fout = open(os.path.join(conf.get('upload_dir'), savefile), 'w')
            fout.write(content)
            fout.close()

            response.write(conf.get('upload_url_prefix') + savefile)
        else:
            return bad_request()
    else:
        # bad request
        return bad_request()

    return response
Ejemplo n.º 5
0
def testdynamiccomponent(request):
    resp = HTTPResponse()
    resp.write(
        etree.tostring(
            etree.XML(
                parse_dynamic_content_xml(
                    os.path.join(TEMPLATES_FOLDER, 'basexml/test.xml'),
                    {}))).decode('utf-8'))
    return resp
Ejemplo n.º 6
0
    def process(self,
                url=None,
                method='GET',
                data=None,
                environ=None,
                secure=False,
                content_type='html',
                route_name=None,
                encoding='UTF-8'):
        content_type_to_http_protocol_content_types = {
            'html': 'text/html; charset={}'.format(encoding),
            'json': 'application/json; charset={}'.format(encoding)
        }
        original_content_type = content_type
        content_type = content_type_to_http_protocol_content_types[
            content_type]
        if route_name:
            url = router.path_for(route_name)
        if url is None:
            raise ValueError(
                'Please provide correct url for request or proper route_name')
        data = data or {}
        method = method.upper()
        response = HTTPResponse()
        r = self._base_environ()
        r.update({
            'PATH_INFO': url,
            'REQUEST_METHOD': str(method),
            'SERVER_PORT': str('443') if secure else str('80'),
            'wsgi.url_scheme': str('https') if secure else str('http'),
        })
        if method in ('POST', 'PUT'):
            formatter = get_formatter_for(original_content_type)
            data = formatter.format(data).encode(encoding)
            r.update({
                'CONTENT_LENGTH': len(data),
                'CONTENT_TYPE': str(content_type),
                'wsgi.input': FakePayload(data),
            })
        elif method == 'GET':
            # WSGI requires latin-1 encoded strings.
            r['QUERY_STRING'] = bytes(parse.urlencode(data),
                                      'iso-8859-1').decode()
        r.update(environ or {})

        def wsgi_response_handler(response, status_string, headers):
            response.content_type = [
                header[1] for header in headers
                if header[0].lower() == 'content-type'
            ].pop()
            response.status_code = HTTP_STATUS_STRING_TO_CODE[status_string]
            response.headers = headers

        output = application(r, partial(wsgi_response_handler, response))
        response.buffer = output
        return response
    def get(self):
        fortunes = db_session.query(Fortune).all()
        fortunes.append(Fortune(id=0, message="Additional fortune added at request time."))
        fortunes.sort(key=attrgetter("message"))
        template = template_engine.get_template("fortune.html")
        template_html = template.render({"fortunes": fortunes})		

        response = HTTPResponse()
        response.write(template_html)
        return response
Ejemplo n.º 8
0
def datatoZigBee(request):
    response = HTTPResponse()
    try:
        id= int(request.get_param('id'))
        data=request.get_param('data').encode("ascii")
        addr=dictionary[id]['addr']
        addr_long=dictionary[id]['addr_long']
        sendToZigBee(addr_long, addr, data)
    except Exception as e:
        print ("Error enviando datos "+ str(e))
        response.status_code = 401
    return response
Ejemplo n.º 9
0
    def get(self, skip_body=False):

        mime_type, encoding = mimetypes.guess_type(self.filepath)
        response = HTTPResponse(mime_type or 'plain/text', encoding)
        if not skip_body:
            response.headers.append(HTTP_HEADER_ACCEPT_RANGE_NONE)
            file = open(self.filepath, 'rb')
            try:
                response.write_bytes(file.read())
            finally:
                file.close()
        return response
Ejemplo n.º 10
0
    def get(self, skip_body=False):

        mime_type, encoding = mimetypes.guess_type(self.filepath)
        response = HTTPResponse(mime_type or 'plain/text', encoding)
        if not skip_body:
            response.headers.append(HTTP_HEADER_ACCEPT_RANGE_NONE)
            file = open(self.filepath, 'rb')
            try:
                response.write_bytes(file.read())
            finally:
                file.close()
        return response
Ejemplo n.º 11
0
    def get(self):
        fortunes = db_session.query(Fortune).all()
        fortunes.append(Fortune(id=0, message="Additional fortune added at request time."))
        fortunes.sort(key=attrgetter("message"))
        engine = Engine(loader=FileLoader(["views"]), extensions=[CoreExtension()])
        template = engine.get_template("fortune.html")
        for f in fortunes:
            f.message = bleach.clean(f.message)
        template_html = template.render({"fortunes": fortunes})		

        response = HTTPResponse()
        response.write(template_html)
        return response
Ejemplo n.º 12
0
    def post(self):

        try:
            form = self.request.form
            code = form['code'][0]
        except:
            return bad_request_with_detail(
                'No data posted, or data in incorrect format')

        params = {
            "grant_type": "authorization_code",
            "redirect_uri": config.SPOTIFY_CALLBACK_URL,
            "code": code
        }

        token_response = requests.post(config.SPOTIFY_TOKEN_ENDPOINT,
                                       data=params,
                                       headers=auth_header,
                                       verify=True)

        response = HTTPResponse()
        response.content_type = 'application/json'
        response.status_code = token_response.status_code

        if token_response.status_code == 200:
            json_response = token_response.json()
            refresh_token = json_response["refresh_token"]
            encrypted_token = crypt.encrypt(refresh_token)
            json_response["refresh_token"] = encrypted_token
            response_body = json.dumps(json_response)
            response.write(response_body)
        else:
            response.write_bytes(token_response.content)

        return response
Ejemplo n.º 13
0
    def post(self):
        """
        Handle HTTP POST.
        """

        method = self.get_method()
        body = self.get_body()

        # TODO handle method exception.
        result = method(**body)
        payload = self.encoder.encode(result)

        response = HTTPResponse(content_type="application/json")
        response.status_code = 200
        response.write(payload)

        return response
Ejemplo n.º 14
0
    def post(self):
        """
        Handle HTTP POST.
        """

        method = self.get_method()
        body = self.get_body()

        # TODO handle method exception.
        result = method(**body)
        payload = self.encoder.encode(result)

        response = HTTPResponse(content_type="application/json")
        response.status_code = 200
        response.write(payload)

        return response
Ejemplo n.º 15
0
def welcome(request):
    message, error = '', ''
    if request.method == 'POST':
        errors = {}
        if not captcha.validate(request, errors, gettext=lambda s: s):
            error = errors['turing_number'][-1]
        else:
            message = 'Well done!'
    challenge_code = captcha.get_challenge_code(request)
    response = HTTPResponse()
    response.write("""
<html><head><style>
span {color: green;}
span.error {color:red;}
input[type=text] {width:200;text-transform: uppercase;}
#captcha {display:block; width:200; height:75}
</style></head><body>
<html><body>
<h2>Captcha Verification: wheezy.http demo</h2>
<span><b>%s</b></span>
<form method="post">
<p>Please enter the text from image:</p>
<p>
    <label for="turing_number">
        <img id="captcha" src="/captcha.jpg?c=%s" />
        <input type="hidden" name="c" value="%s" />
    </label>
    <input id="turing_number" name="turing_number" type="text"
        maxlength="4" autocomplete="off" />
    <span class="error">%s</span>
</p>
<p><input type="submit" value="Verify"></p>
</form>
<script>
window.onload=function()
{
    c = document.getElementById('captcha');
    c.onclick = function() {
        this.src=this.src.replace(/&r=\d+/g,'') + '&r=' + \
            Math.floor(Math.random() * 100 + 1);
    };
}
</script>
</body></html>
    """ % (message, challenge_code, challenge_code, error))
    return response
Ejemplo n.º 16
0
    def post(self):

        try:
            form = self.request.form
            code = form["code"][0]
        except:
            return bad_request_with_detail("No data posted, or data in incorrect format")

        params = {"grant_type": "authorization_code", "redirect_uri": config.SPOTIFY_CALLBACK_URL, "code": code}

        token_response = requests.post(config.SPOTIFY_TOKEN_ENDPOINT, data=params, headers=auth_header, verify=True)

        response = HTTPResponse()
        response.content_type = "application/json"
        response.status_code = token_response.status_code

        if token_response.status_code == 200:
            json_response = token_response.json()
            refresh_token = json_response["refresh_token"]
            encrypted_token = crypt.encrypt(refresh_token)
            json_response["refresh_token"] = encrypted_token
            response_body = json.dumps(json_response)
            response.write(response_body)
        else:
            response.write_bytes(token_response.content)

        return response
Ejemplo n.º 17
0
    def post(self):

        try:
            form = self.request.form
            encrypted_token = form["refresh_token"][0]
            token = crypt.decrypt(encrypted_token)
        except:
            return bad_request_with_detail("No data posted, or data in incorrect format")

        params = {"grant_type": "refresh_token", "refresh_token": token}

        token_response = requests.post(config.SPOTIFY_TOKEN_ENDPOINT, data=params, headers=auth_header, verify=True)

        response = HTTPResponse()
        response.content_type = "application/json"
        response.status_code = token_response.status_code
        response.write_bytes(token_response.content)
        return response
Ejemplo n.º 18
0
    def get(self):
        con = session()
        repo = Repository(con)

        CONTENT_TYPE_XML='text/xml'
        CONTENT_TYPE_XML_RSP=CONTENT_TYPE_XML+'; charset=utf-8'

        if DEBUG:
            base_url = 'http://192.168.72.100:8080'
        else:
            base_url = 'http://shoboi.net'

        feed = feedgenerator.Atom1Feed(
            title = 'しょぼいろだ。',
            link = 'http://shobi.net/',
            feed_url = 'http://shoboi.net/atom',
            description = u'エロも笑いも虹も惨事もしょぼいろだで共有してね',
            author_name=u'しょぼい。',
            language = u"ja",
            pubdate = datetime.utcnow()
        )

        upimages = repo.list_upimages()
        for idx, i in enumerate(upimages):
            feed.add_item(
                title = i.title or 'タイトルなし',
                link = '%s/detail/%s' % (base_url, i.id),
                description = """<![CDATA[
                    <a href="%s/detail/%s">
                      <img src="%s/img/%s">
                    </a>
                ]]>""" % (base_url, i.id, base_url, i.thumb),
                author_name = i.author or '名無し',
                pubdate = datetime.now()
            )
            if idx >= 4: # 5件まで
                break;

        response = HTTPResponse()
        content_type = ('Content-Type', CONTENT_TYPE_XML_RSP)
        response.headers[0] = content_type
        response.write(feed.writeString('utf-8'))
        response.cache_dependency = ('d_atom', )
        return response
Ejemplo n.º 19
0
    def process(self, url=None, method='GET', data=None, environ=None, secure=False,
                content_type='html', route_name=None, encoding='UTF-8'):
        content_type_to_http_protocol_content_types = {
            'html': 'text/html; charset={}'.format(encoding),
            'json': 'application/json; charset={}'.format(encoding)
        }
        original_content_type = content_type
        content_type = content_type_to_http_protocol_content_types[content_type]
        if route_name:
            url = router.path_for(route_name)
        if url is None:
            raise ValueError('Please provide correct url for request or proper route_name')
        data = data or {}
        method = method.upper()
        response = HTTPResponse()
        r = self._base_environ()
        r.update({
            'PATH_INFO': url,
            'REQUEST_METHOD': str(method),
            'SERVER_PORT': str('443') if secure else str('80'),
            'wsgi.url_scheme': str('https') if secure else str('http'),
        })
        if method in ('POST', 'PUT'):
            formatter = get_formatter_for(original_content_type)
            data = formatter.format(data).encode(encoding)
            r.update({
                'CONTENT_LENGTH': len(data),
                'CONTENT_TYPE': str(content_type),
                'wsgi.input': FakePayload(data),
            })
        elif method == 'GET':
            # WSGI requires latin-1 encoded strings.
            r['QUERY_STRING'] = bytes(parse.urlencode(data), 'iso-8859-1').decode()
        r.update(environ or {})

        def wsgi_response_handler(response, status_string, headers):
            response.content_type = [header[1] for header in headers if header[0].lower() == 'content-type'].pop()
            response.status_code = HTTP_STATUS_STRING_TO_CODE[status_string]
            response.headers = headers

        output = application(r, partial(wsgi_response_handler, response))
        response.buffer = output
        return response
Ejemplo n.º 20
0
    def wrap_request(self, request, *args, **kwargs):
        '''
        Prepares data and pass control to `restea.Resource` object

        :returns: :class: `wheezy.http.HTTPResponse`
        '''
        data_format, kwargs = self._get_format_name(kwargs)
        formatter = formats.get_formatter(data_format)

        resource = self._resource_class(
            WheezyRequestWrapper(request), formatter
        )
        res, status_code, content_type = resource.dispatch(*args, **kwargs)

        response = HTTPResponse(
            content_type=content_type,
        )
        response.write(res)
        response.status_code = status_code
        return response
Ejemplo n.º 21
0
 def get(self, skip_body=False):
     route_args = self.route_args
     path = route_args['path']
     assert path
     abspath = os.path.abspath(os.path.join(self.root, path))
     if not abspath.startswith(self.root):
         return forbidden()
     if not os.path.exists(abspath):
         return not_found()
     if not os.path.isfile(abspath):
         return forbidden()
     mime_type, encoding = mimetypes.guess_type(abspath)
     response = HTTPResponse(mime_type or 'plain/text', encoding)
     if not skip_body:
         response.headers.append(HTTP_HEADER_ACCEPT_RANGE_NONE)
         file = open(abspath, 'rb')
         try:
             response.write_bytes(file.read())
         finally:
             file.close()
     return response
Ejemplo n.º 22
0
 def handler(request):
     if self.challenge_key not in request.query:
         return bad_request()
     challenge_code = last_item_adapter(
         request.query)[self.challenge_key]
     turing_number = ''.join(random.sample(self.chars, self.max_chars))
     if not self.cache.set(self.prefix + challenge_code,
                           (int(time()), turing_number),
                           self.timeout, self.namespace):
         return bad_request()
     response = HTTPResponse(content_type)
     self.image(turing_number).save(
         FileAdapter(response), format, **options)
     return response
Ejemplo n.º 23
0
    def post(self):

        try:
            form = self.request.form
            encrypted_token = form['refresh_token'][0]
            token = crypt.decrypt(encrypted_token)
        except:
            return bad_request_with_detail(
                'No data posted, or data in incorrect format')

        params = {"grant_type": "refresh_token", "refresh_token": token}

        token_response = requests.post(config.SPOTIFY_TOKEN_ENDPOINT,
                                       data=params,
                                       headers=auth_header,
                                       verify=True)

        response = HTTPResponse()
        response.content_type = 'application/json'
        response.status_code = token_response.status_code
        response.write_bytes(token_response.content)
        return response
Ejemplo n.º 24
0
def nodes(request):
    dic=get_nodes()
    response = HTTPResponse()
    response.write(json.dumps(dic))
    return response
Ejemplo n.º 25
0
 def get(self):
     response = HTTPResponse()
     response.write('hello world')
     return response
Ejemplo n.º 26
0
def request_db_read(request):
    response = HTTPResponse()
    response.headers = [(CONTENT_TYPE, CONTENT_TYPE_JSON)]
    response.write(response_db_read_queries())
    return response
Ejemplo n.º 27
0
 def _error_response(self, request, error):
     resp = HTTPResponse()
     resp.status_code = ERROR_STATUS_CODE
     resp.write_bytes(json.dumps({'error': error}))
     return resp
Ejemplo n.º 28
0
 def get(self):
     response = HTTPResponse()
     response.headers = [(CONTENT_TYPE, CONTENT_TYPE_JSON)]
     response.write(response_db_write_queries())
     return response
Ejemplo n.º 29
0
def welcome(request):
    response = HTTPResponse()
    response.write('Hello World!')
    return response
Ejemplo n.º 30
0
 def get(self):
     response = HTTPResponse()
     response.write('Hello World!')
     return response
Ejemplo n.º 31
0
 def get(self):
     response = HTTPResponse()
     response.write(PING_MESSAGE.format(app='wheezyweb'))
     return response
Ejemplo n.º 32
0
 def post(self):
     data = self.request.form
     insert(data)
     response = HTTPResponse()
     response.status_code = 201
     return response
Ejemplo n.º 33
0
 def get(self):
     response = HTTPResponse()
     response.headers = [(CONTENT_TYPE, CONTENT_TYPE_JSON)]
     response.write(response_json())
     return response
Ejemplo n.º 34
0
 def get(self):
     response = HTTPResponse()
     response.write('Hello World!')
     return response
Ejemplo n.º 35
0
 def get(self):
     response = HTTPResponse()
     response.write('PING_SUCCESS')
     return response
Ejemplo n.º 36
0
 def get(self):
     response = HTTPResponse(content_type="application/json; charset=UTF-8")
     response.write(ujson.dumps({"test": True}))
     return response
Ejemplo n.º 37
0
 def get(self):
     response = HTTPResponse()
     response.headers = [(CONTENT_TYPE, CONTENT_TYPE_PLAIN)]
     response.write(response_cached())
     return response
Ejemplo n.º 38
0
def get_id(request):
    global sink_info
       
    response = HTTPResponse()
    response.write(json.dumps(sink_info))
    return response
Ejemplo n.º 39
0
def data(request):
    id= int(request.get_param('id'))
    data=get_data(id)
    response = HTTPResponse()
    response.write(json.dumps(data))
    return response
Ejemplo n.º 40
0
def welcome(request):
    response = HTTPResponse()
    response.write('Server is up!')
    return response
Ejemplo n.º 41
0
def json_view(request):
    response = HTTPResponse()
    json_data = {"message": "Hello, World!"}
    data = json.dumps(json_data)
    response.write(data)
    return response
Ejemplo n.º 42
0
def request_cache_read(request):
    response = HTTPResponse()
    response.headers = [(CONTENT_TYPE, CONTENT_TYPE_PLAIN)]
    response.write(response_cached())
    return response
Ejemplo n.º 43
0
def ping(request):
    response = HTTPResponse()
    response.write('Pong!')
    return response
Ejemplo n.º 44
0
 def get(self):
     response = HTTPResponse()
     response.headers = [(CONTENT_TYPE, CONTENT_TYPE_HTML)]
     response.write(response_html())
     return response
Ejemplo n.º 45
0
def plaintext(request):
    response = HTTPResponse()
    response.headers = [("Content-Type", "text/plain; charset=UTF-8")]
    response.write("Hello, world!")
    return response
Ejemplo n.º 46
0
def test(request):
    response = HTTPResponse()
    response.write('<html><body>Hello World</body></html>')
    return response
Ejemplo n.º 47
0
	def get(self):
		response = HTTPResponse()
		response.write('Hello,World~~get')
		return response
Ejemplo n.º 48
0
 def _error_response(self, request, error):
     resp = HTTPResponse()
     resp.status_code = ERROR_STATUS_CODE
     resp.write_bytes(json.dumps({'error': error}))
     return resp
Ejemplo n.º 49
0
 def get(self):
     response = HTTPResponse(content_type="application/json; charset=UTF-8")
     response.write(ujson.dumps({"test": True}))
     return response
Ejemplo n.º 50
0
def request_html(request):
    response = HTTPResponse()
    response.headers = [(CONTENT_TYPE, CONTENT_TYPE_HTML)]
    response.write(response_html())
    return response
Ejemplo n.º 51
0
 def get(self):
     response = HTTPResponse()
     quote = {'message': 'Hello, World!'}
     response.write(json.dumps(quote))
     return response
Ejemplo n.º 52
0
def welcome(request):
    response = HTTPResponse()
    response.write('Hello World!')
    return response
Ejemplo n.º 53
0
Archivo: fibaas.py Proyecto: reu/fibaas
 def get(self):
     number = int(self.route_args["number"])
     response = HTTPResponse()
     response.write(str(fib(number)))
     return response
Ejemplo n.º 54
0
def request_slow(request):
    response = HTTPResponse()
    response.headers = [(CONTENT_TYPE, CONTENT_TYPE_PLAIN)]
    response.write(response_slow())
    return response
Ejemplo n.º 55
0
 def get(self):
     rows = find_all()
     response = HTTPResponse()
     response.write(rows)
     return response
Ejemplo n.º 56
0
def welcome(request):
    response = HTTPResponse()
    response.write('Server is up!')
    return response