コード例 #1
0
ファイル: server_werkzeug_test.py プロジェクト: cinp/python
def test_werkzeug_response():
    resp = Response(201, {'hi': 'there'}, {'hdr': 'big'})
    assert resp.header_map == {'hdr': 'big'}
    wresp = WerkzeugResponse(resp).asJSON()
    assert wresp.status_code == 201
    assert wresp.headers == Headers([('hdr', 'big'),
                                     ('Content-Type',
                                      'application/json;charset=utf-8'),
                                     ('Content-Length', '15')])
    assert wresp.data == '{"hi": "there"}'.encode('utf-8')

    resp = Response(200, 'more stuff', {'count': 20})
    wresp = WerkzeugResponse(resp).asJSON()
    assert wresp.status_code == 200
    assert wresp.headers == Headers([('count', 20),
                                     ('Content-Type',
                                      'application/json;charset=utf-8'),
                                     ('Content-Length', '12')])
    assert wresp.data == '"more stuff"'.encode('utf-8')

    resp = Response(404, ['one', 2, {'3': 'three'}])
    wresp = WerkzeugResponse(resp).asJSON()
    assert wresp.status_code == 404
    assert wresp.headers == Headers([('Content-Type',
                                      'application/json;charset=utf-8'),
                                     ('Content-Length', '26')])
    assert wresp.data == '["one", 2, {"3": "three"}]'.encode('utf-8')

    with pytest.raises(ValueError):
        WerkzeugResponse('test')
コード例 #2
0
def upload_handler(request):  # TODO: also support multi-part
    if request.verb == 'OPTIONS':
        header_map = {}
        header_map['Allow'] = 'OPTIONS, POST'
        header_map['Cache-Control'] = 'max-age=0'
        header_map['Access-Control-Allow-Methods'] = header_map['Allow']
        header_map[
            'Access-Control-Allow-Headers'] = 'Accept, Content-Type, Content-Disposition'

        return Response(200, data=None, header_map=header_map)

    if request.verb != 'POST':
        return Response(400,
                        data='Invalid Verb (HTTP Method)',
                        content_type='text')

    if request.header_map.get('CONTENT-TYPE',
                              None) != 'application/octet-stream':
        return Response(400, data='Invalid Content-Type', content_type='text')

    content_disposition = request.header_map.get('CONTENT-DISPOSITION', None)
    if content_disposition is not None:
        match = INLINE_CONTENT_DISPOSITION.match(content_disposition)
        if not match:
            return InvalidRequest(
                message='Invalid Content-Disposition').asResponse()
        filename = match.groups(1)[0]
    else:
        filename = None

    file_writer, refname = _localFileWriter(filename)

    buff = request.read(CHUNK_SIZE)
    while buff:
        file_writer.write(buff)
        buff = request.read(CHUNK_SIZE)

    file_writer.close()

    return Response(202, data={'uri': 'djfh://{0}'.format(refname)})
コード例 #3
0
def test_response():
  resp = Response( 200 )
  assert resp.http_code == 200
  assert resp.data is None
  assert resp.header_map == {}
  assert resp.asJSON() is None

  resp = Response( 201, { 'hi': 'there' } )
  assert resp.http_code == 201
  assert resp.data == { 'hi': 'there' }
  assert resp.header_map == {}
  assert resp.asJSON() is None  # yea, still none, base Responose dosen't asXXXX anything

  resp = Response( 201, 'more stuff', { 'hdr': 'big' } )
  assert resp.http_code == 201
  assert resp.data == 'more stuff'
  assert resp.header_map == { 'hdr': 'big' }
  assert resp.asJSON() is None  # yea, still none, base Responose dosen't asXXXX anything
コード例 #4
0
def handler(request):
    match = url_regex.match(request.uri.lower())
    if not match:
        return Response(400, data='Invalid config uri', content_type='text')

    (request_type, _, config_uuid, structure_id, foundation_locator,
     ip_address, _, _, _) = match.groups()

    target = None

    if config_uuid is not None:
        try:
            target = Structure.objects.get(config_uuid=config_uuid[2:])
        except Structure.DoesNotExist:
            return Response(404,
                            data='Config UUID Not Found',
                            content_type='text')

    elif structure_id is not None:
        try:
            target = Structure.objects.get(pk=int(structure_id[2:]))
        except Structure.DoesNotExist:
            return Response(404,
                            data='Structure Not Found',
                            content_type='text')

    elif foundation_locator is not None:
        try:
            target = Foundation.objects.get(pk=foundation_locator[2:]).subclass
        except Foundation.DoesNotExist:
            return Response(404,
                            data='Foundation Not Found',
                            content_type='text')

    else:
        if ip_address is not None:
            address = BaseAddress.lookup(ip_address[2:])
        else:
            address = BaseAddress.lookup(request.remote_addr)

        if address is None:
            return Response(404, data='Address Not Found', content_type='text')

        address = address.subclass
        if address.type == 'Address':
            target = address.networked.subclass
        else:
            target = address

    if target is None:
        return Response(500, data='Target is missing', content_type='text')

    data = None
    config = getConfig(target)

    if request_type in ('boot_script', 'pxe_template'):
        pxe = None
        if isinstance(target, Structure):
            pxe = target.provisioning_interface.pxe
        elif isinstance(target, Foundation):
            pxe = target.structure.provisioning_interface.pxe
        elif isinstance(target, DynamicAddress):
            pxe = target.pxe

        if pxe is None:
            return Response(200, data='', content_type='text')

        if request_type == 'boot_script':
            template = '#!ipxe\n\n' + pxe.boot_script

        elif request_type == 'pxe_template':
            template = pxe.template

        data = renderTemplate(template, config)
        return Response(200, data=data, content_type='text')

    elif request_type == 'config':
        _fromPythonMap(
            config
        )  # this does not go out CInP's converter, we need to make the python dict JSON encodable our selves
        return Response(200, data=mergeValues(config))

    return Response(400, data='Invalid request type', content_type='text')
コード例 #5
0
ファイル: config_handler.py プロジェクト: tannoa2/contractor
def handler( request ):
  if not re.match( '^/config/[a-z_]+/([sf][0-9]+)?$', request.uri ):
    return Response( 400, data='Invalid config uri', content_type='text' )

  ( _, _, request_type, target_id ) = request.uri.split( '/' )

  target = None
  interface = None

  if len( target_id ) > 0:
    if target_id[0] == 's':
      try:
        target = Structure.objects.get( pk=int( target_id[ 1: ] ) )
      except Structure.DoesNotExist:
        return Response( 404, data='Structure Not Found', content_type='text' )

    elif target_id[0] == 'f':
      try:
        target = Foundation.objects.get( pk=int( target_id[ 1: ] ) )
      except Foundation.DoesNotExist:
        return Response( 404, data='Foundation Not Found', content_type='text' )

    else:
      return Response( 500, data='Target Confusion', content_type='text' )

    interface = target.provisioning_interface

  else:
    print( 'Getting config goodies for "{0}"'.format( request.remote_addr ) )
    address = BaseAddress.lookup( request.remote_addr )
    if address is None:
      return Response( 404, data='Address Not Found', content_type='text' )

    address = address.subclass
    if address.type != 'Address':
      return Response( 404, data='Address Not Valid', content_type='text' )

    target = address.networked.subclass
    try:
      if isinstance( target, Structure ):
        interface = target.foundation.interfaces.get( name=address.interface_name )
      else:
        interface = target.interfaces.get( name=address.interface_name )

    except NetworkInterface.DoesNotExist:
      return Response( 404, data='Interface Not Found', content_type='text' )

  if target is None or interface is None:
    return Response( 500, data='Target/Interface is missing', content_type='text' )

  data = None
  config = getConfig( target )

  if request_type in ( 'boot_script', 'pxe_template' ):
    pxe = interface.pxe
    if pxe is None:
      return Response( 200, data='', content_type='text' )

    if request_type == 'boot_script':
      template = Template( '#!ipxe\n\n' + pxe.boot_script )

    elif request_type == 'pxe_template':
      template = Template( pxe.template )

    data = template.render( Context( config ) )
    print( 'config_handler sending "{0}" to "{1}"\n    -----------    '.format( request_type, request.remote_addr ) )
    print( data )
    print( '    -----------    ')
    return Response( 200, data=data, content_type='text' )

  elif request_type == 'config':
    _fromPythonMap( config )
    return Response( 200, data=json.dumps( config ) )

  return Response( 400, data='Invalid request type', content_type='text' )