Python urllib.request 模块,method() 实例源码

我们从Python开源项目中,提取了以下44个代码示例,用于说明如何使用urllib.request.method()

项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
def index(request):
    if request.method == 'POST':
        form = PathAnalysisForm(request.POST)
        if  form.is_valid():
            query = form.cleaned_data['search']
            print(query)
            #here is where the magic happens!
            #search in kegg
#            data = kegg_rest_request('list/pathway/hsa')
#            pathways = kegg_rest_request('find/pathway/%s' % (query))
            pathways = Pathway.objects.filter(Q(name__icontains=query))
            # print pathways

    else:
        form = PathAnalysisForm()
#        pathways = kegg_rest_request('list/pathway/hsa')
        pathways = Pathway.objects.all()    


    return render_to_response('pathway_analysis/index.html', {'form': form, 'pathways': pathways}, context_instance=RequestContext(request))
项目:gemstone    作者:vladcalin    | 项目源码 | 文件源码
def call_method(self, method_name_or_object, params=None):
        """
        Calls the ``method_name`` method from the given service and returns a
        :py:class:`gemstone.client.structs.Result` instance.

        :param method_name_or_object: The name of te called method or a ``MethodCall`` instance
        :param params: A list of dict representing the parameters for the request
        :return: a :py:class:`gemstone.client.structs.Result` instance.
        """
        if isinstance(method_name_or_object, MethodCall):
            req_obj = method_name_or_object
        else:
            req_obj = MethodCall(method_name_or_object, params)
        raw_response = self.handle_single_request(req_obj)
        response_obj = Result(result=raw_response["result"], error=raw_response['error'],
                              id=raw_response["id"], method_call=req_obj)
        return response_obj
项目:gemstone    作者:vladcalin    | 项目源码 | 文件源码
def call_method_async(self, method_name_or_object, params=None):
        """
        Calls the ``method_name`` method from the given service asynchronously
        and returns a :py:class:`gemstone.client.structs.AsyncMethodCall` instance.

        :param method_name_or_object: The name of te called method or a ``MethodCall`` instance
        :param params: A list of dict representing the parameters for the request
        :return: a :py:class:`gemstone.client.structs.AsyncMethodCall` instance.
        """
        thread_pool = self._get_thread_pool()

        if isinstance(method_name_or_object, MethodCall):
            req_obj = method_name_or_object
        else:
            req_obj = MethodCall(method_name_or_object, params)

        async_result_mp = thread_pool.apply_async(self.handle_single_request, args=(req_obj,))
        return AsyncMethodCall(req_obj=req_obj, async_resp_object=async_result_mp)
项目:gemstone    作者:vladcalin    | 项目源码 | 文件源码
def notify(self, method_name_or_object, params=None):
        """
        Sends a notification to the service by calling the ``method_name``
        method with the ``params`` parameters. Does not wait for a response, even
        if the response triggers an error.

        :param method_name_or_object: the name of the method to be called or a ``Notification``
                                      instance
        :param params: a list of dict representing the parameters for the call
        :return: None
        """
        if isinstance(method_name_or_object, Notification):
            req_obj = method_name_or_object
        else:
            req_obj = Notification(method_name_or_object, params)
        self.handle_single_request(req_obj)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def setUp(self):
        # Create a list of temporary files. Each item in the list is a file
        # name (absolute path or relative to the current working directory).
        # All files in this list will be deleted in the tearDown method. Note,
        # this only helps to makes sure temporary files get deleted, but it
        # does nothing about trying to close files that may still be open. It
        # is the responsibility of the developer to properly close files even
        # when exceptional conditions occur.
        self.tempFiles = []

        # Create a temporary file.
        self.registerFileForCleanUp(support.TESTFN)
        self.text = b'testing urllib.urlretrieve'
        try:
            FILE = open(support.TESTFN, 'wb')
            FILE.write(self.text)
            FILE.close()
        finally:
            try: FILE.close()
            except: pass
项目:daas    作者:havron    | 项目源码 | 文件源码
def check_auth(request): # /auth
  if request.method != 'POST':  
    return _error_response(request, err_exp.E_BAD_REQUEST, "must make POST request")

  form = AuthForm(request.POST)
  if not form.is_valid():
    return _error_response(request, err_exp.E_FORM_INVALID, "user logout form not correctly filled out")

  post_data = form.cleaned_data
  post_encoded = urllib.parse.urlencode(post_data).encode('utf-8')
  req = urllib.request.Request('http://models-api:8000/api/v1/user/auth/', data=post_encoded, method='POST')
  resp_json = urllib.request.urlopen(req).read().decode('utf-8')
  resp = json.loads(resp_json)

  if not resp:
    return _error_response(request, err_exp.E_LOGIN_FAILED, "no response from models API")
  if resp['ok'] == False: # could be much more nuanced. makes web view handle errors
    return _error_response(request, err_exp.E_LOGIN_FAILED, resp)

  # if datetime.datetime.now() - resp['resp']['date_created'] > : ... expiration of auth token not implemented.
  return _success_response(request, resp['resp'])



# Look into https://github.com/kencochrane/django-defender for blocking brute force login requests
项目:daas    作者:havron    | 项目源码 | 文件源码
def login(request): # /login
  if request.method != 'POST':  
    return _error_response(request, err_exp.E_BAD_REQUEST, "must make POST request")

  form = LoginForm(request.POST)
  if not form.is_valid():
    return _error_response(request, err_exp.E_FORM_INVALID, "user login form not correctly filled out")

  post_data = form.cleaned_data
  post_encoded = urllib.parse.urlencode(post_data).encode('utf-8')
  req = urllib.request.Request('http://models-api:8000/api/v1/user/login/', data=post_encoded, method='POST')
  resp_json = urllib.request.urlopen(req).read().decode('utf-8')
  resp = json.loads(resp_json)

  if not resp:
    return _error_response(request, err_exp.E_LOGIN_FAILED, "no response from models API")
  if resp['ok'] == False: # could be much more nuanced. makes web view handle errors
    return _error_response(request, err_exp.E_LOGIN_FAILED, resp)

  return _success_response(request, resp['resp'])
项目:daas    作者:havron    | 项目源码 | 文件源码
def logout(request): # /logout
  if request.method != 'POST':  
    return _error_response(request, err_exp.E_BAD_REQUEST, "must make POST request")

  form = AuthForm(request.POST)
  if not form.is_valid():
    return _error_response(request, err_exp.E_FORM_INVALID, "user logout form not correctly filled out")

  post_data = form.cleaned_data
  post_encoded = urllib.parse.urlencode(post_data).encode('utf-8')
  req = urllib.request.Request('http://models-api:8000/api/v1/user/logout/', data=post_encoded, method='POST')
  resp_json = urllib.request.urlopen(req).read().decode('utf-8')
  resp = json.loads(resp_json)

  if not resp:
    return _error_response(request, err_exp.E_LOGIN_FAILED, "no response from models API")
  if resp['ok'] == False: # could be much more nuanced. makes web view handle errors
    return _error_response(request, err_exp.E_LOGIN_FAILED, resp)

  #return _success_response(request, resp['resp'])
  return _success_response(request, "logged out successfully")
项目:daas    作者:havron    | 项目源码 | 文件源码
def my_drones(request): # /my-drones
  if request.method != 'POST':  
    return _error_response(request, err_exp.E_BAD_REQUEST, "must make POST request")

  form = AuthForm(request.POST)
  if not form.is_valid():
    return _error_response(request, err_exp.E_FORM_INVALID, "user logout form not correctly filled out")

  post_data = form.cleaned_data
  post_encoded = urllib.parse.urlencode(post_data).encode('utf-8')
  req = urllib.request.Request('http://models-TODO:8000/api/v1/my-drones/', data=post_encoded, method='POST')
  resp_json = urllib.request.urlopen(req).read().decode('utf-8')
  resp = json.loads(resp_json)

  if not resp:
    return _error_response(request, err_exp.E_LOGIN_FAILED, "no response from models API")
  if resp['ok'] == False: # could be much more nuanced. makes web view handle errors
    return _error_response(request, err_exp.E_LOGIN_FAILED, resp)

  # if datetime.datetime.now() - resp['resp']['date_created'] > : ... expiration of auth token not implemented.
  return _success_response(request, resp['resp'])
项目:daas    作者:havron    | 项目源码 | 文件源码
def search(request): # /search
  if request.method != 'POST':  
    return _error_response(request, err_exp.E_BAD_REQUEST, "must make POST request")

  if not es.indices.exists(index='listing_index'):
    return _error_response(request, 'listings not found')

  resp = []
  res = es.search(index='listing_index', body={'query': {'query_string': {'query': request.POST['query']}}, 'size': 10})
  hits = res['hits']['hits']
  if not hits:
    return _error_response(request, res)
  for hit in hits:
    resp.append(hit['_source']) # parse es source

  return _success_response(request, resp)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def setUp(self):
        # Create a list of temporary files. Each item in the list is a file
        # name (absolute path or relative to the current working directory).
        # All files in this list will be deleted in the tearDown method. Note,
        # this only helps to makes sure temporary files get deleted, but it
        # does nothing about trying to close files that may still be open. It
        # is the responsibility of the developer to properly close files even
        # when exceptional conditions occur.
        self.tempFiles = []

        # Create a temporary file.
        self.registerFileForCleanUp(support.TESTFN)
        self.text = b'testing urllib.urlretrieve'
        try:
            FILE = open(support.TESTFN, 'wb')
            FILE.write(self.text)
            FILE.close()
        finally:
            try: FILE.close()
            except: pass
项目:toshi-services-lib    作者:toshiapp    | 项目源码 | 文件源码
def fetch_impl(self, request):
        req = urllib.request.Request(
            request.url, method=request.method,
            data=request.body, headers=request.headers)

        start_time = time.time()
        try:

            resp = urllib.request.urlopen(req, timeout=request.timeout)

        except urllib.error.HTTPError as e:

            resp = e

        except socket.timeout as e:

            return ToshiHTTPResponse(request, 599)

        end_time = time.time()

        code = resp.code
        buffer = BytesIO(resp.read())
        headers = dict(resp.info())

        return ToshiHTTPResponse(request, code, headers=headers, buffer=buffer, request_time=end_time - start_time)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def setUp(self):
        # Create a list of temporary files. Each item in the list is a file
        # name (absolute path or relative to the current working directory).
        # All files in this list will be deleted in the tearDown method. Note,
        # this only helps to makes sure temporary files get deleted, but it
        # does nothing about trying to close files that may still be open. It
        # is the responsibility of the developer to properly close files even
        # when exceptional conditions occur.
        self.tempFiles = []

        # Create a temporary file.
        self.registerFileForCleanUp(support.TESTFN)
        self.text = b'testing urllib.urlretrieve'
        try:
            FILE = open(support.TESTFN, 'wb')
            FILE.write(self.text)
            FILE.close()
        finally:
            try: FILE.close()
            except: pass
项目:FaceRecognitionAPI    作者:wassgha    | 项目源码 | 文件源码
def train(request):
    # check to see if this is a GET request
    if request.method == "GET":
        # check to see if an image was uploaded
        if request.GET.get("imageBase64", None) is not None and request.GET.get("user", None) is not None :
            # grab the uploaded image
            image = _grab_image(base64_string=request.GET.get("imageBase64", None))
            image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
            rects = detector.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5,
                minSize=(30, 30), flags=0)

            # construct a list of bounding boxes from the detection
            rects = [(int(x), int(y), int(x + w), int(y + h)) for (x, y, w, h) in rects]
            if len(rects) == 0:
                return JsonResponse({"error" : "No faces detected"})
            else :
                x, y, w, h = rects[0]
                cv2.imwrite( TRAINED_FACES_PATH + "/" +  str(request.GET.get("user", None)) + "/" + str(uuid.uuid4()) + ".jpg", image[y:h, x:w] );
    return JsonResponse({"success" : True})
项目:mendelmd    作者:raonyguimaraes    | 项目源码 | 文件源码
def view(request, pathway_id):
    print(pathway_id)

#    pathway_data = kegg_rest_request('get/hsa%s' % (pathway_id))
    pathway = Pathway.objects.get(kegg=pathway_id)


    pathway.genes = pathway.genes.split(',')
    print(pathway.genes)

#    genes = parse_genes(pathway_data)
#    pathway = {}
#    pathway['name'] = pathway_data.split('\n')[1].replace('NAME', '') 
#    #get gene_ids
#    genelist = []
#    for gene in genes:
#        
#        genelist.append('hsa:%s' % gene['id'])
##        print gene['id']
#    gene_url = '+'.join(genelist)
#    url = '/conv/ncbi-geneid/%s' % (gene_url)
#    results = kegg_rest_request(url)
    #print results


    #if request.method == 'GET':
    return render_to_response('pathway_analysis/view.html', {'pathway':pathway}, context_instance=RequestContext(request))
项目:gemstone    作者:vladcalin    | 项目源码 | 文件源码
def build_request_body(self, method_name, params, id=None):
        request_body = {
            "jsonrpc": "2.0",
            "method": method_name,
            "params": params

        }
        if id:
            request_body['id'] = id
        return request_body
项目:gemstone    作者:vladcalin    | 项目源码 | 文件源码
def build_http_request_obj(self, request_body):
        request = urllib.request.Request(self.url)
        request.add_header("Content-Type", "application/json")
        request.add_header("User-Agent", "gemstone-client")
        request.data = json.dumps(request_body).encode()
        request.method = "POST"
        return request
项目:django-g-recaptcha    作者:deltaskelta    | 项目源码 | 文件源码
def validate_captcha(view):
    """
    Decorator to validate a captcha based on settings

    from g_recaptcha.validate_recaptcha import validate_captcha

    @validate_Captcha
    def a_view():
        ...
    """

    def wrap(request, *args, **kwargs):

        def failure_http():
            return render(request, 'captcha_fail.html',)
        def failure_ajax():
            return HttpResponse('There was a problem with the captcha, please try again')

        if request.method == 'POST':
            url = "https://www.google.com/recaptcha/api/siteverify"
            values = {
                'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
                'response': request.POST.get('g-recaptcha-response', None),
                'remoteip': request.META.get("REMOTE_ADDR", None),
            }

            data = urllib.parse.urlencode(values)
            req = urllib.request.Request(url, data)
            response = urllib.request.urlopen(req)
            result = json.loads(response.read())

            # result["success"] will be True on a success
            if result["success"]:
                return view(request, *args, **kwargs)
            elif request.is_ajax():
                return failure_ajax()
            else:
                return failure_http()

        return view(request, *args, **kwargs)
    return wrap
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_close(self):
        # Test close() by calling it here and then having it be called again
        # by the tearDown() method for the test
        self.returned_obj.close()
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def help_inputtype(self, given, test_type):
        """Helper method for testing different input types.

        'given' must lead to only the pairs:
            * 1st, 1
            * 2nd, 2
            * 3rd, 3

        Test cannot assume anything about order.  Docs make no guarantee and
        have possible dictionary input.

        """
        expect_somewhere = ["1st=1", "2nd=2", "3rd=3"]
        result = urllib.parse.urlencode(given)
        for expected in expect_somewhere:
            self.assertIn(expected, result,
                         "testing %s: %s not found in %s" %
                         (test_type, expected, result))
        self.assertEqual(result.count('&'), 2,
                         "testing %s: expected 2 '&'s; got %s" %
                         (test_type, result.count('&')))
        amp_location = result.index('&')
        on_amp_left = result[amp_location - 1]
        on_amp_right = result[amp_location + 1]
        self.assertTrue(on_amp_left.isdigit() and on_amp_right.isdigit(),
                     "testing %s: '&' not located in proper place in %s" %
                     (test_type, result))
        self.assertEqual(len(result), (5 * 3) + 2, #5 chars per thing and amps
                         "testing %s: "
                         "unexpected number of characters: %s != %s" %
                         (test_type, len(result), (5 * 3) + 2))
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_with_method_arg(self):
        Request = urllib.request.Request
        request = Request("http://www.python.org", method='HEAD')
        self.assertEqual(request.method, 'HEAD')
        self.assertEqual(request.get_method(), 'HEAD')
        request = Request("http://www.python.org", {}, method='HEAD')
        self.assertEqual(request.method, 'HEAD')
        self.assertEqual(request.get_method(), 'HEAD')
        request = Request("http://www.python.org", method='GET')
        self.assertEqual(request.get_method(), 'GET')
        request.method = 'HEAD'
        self.assertEqual(request.get_method(), 'HEAD')
项目:daas    作者:havron    | 项目源码 | 文件源码
def register(request): # /register
  if request.method != 'POST':  
    return _error_response(request, err_exp.E_BAD_REQUEST, "must make POST request")

  form = RegisterForm(request.POST)
  if not form.is_valid():
    return _error_response(request, err_exp.E_FORM_INVALID, "user registration form not correctly filled out")

  post_data = form.cleaned_data
  post_data['password'] = hashers.make_password(post_data['password1']) # get first validated password and hash it
  post_data['date_joined'] = datetime.datetime.now()
  post_data['is_active'] = True
  post_data['email_address'] = post_data['email1'] 

  post_encoded = urllib.parse.urlencode(post_data).encode('utf-8')
  req = urllib.request.Request('http://models-api:8000/api/v1/user/create/', data=post_encoded, method='POST')
  resp_json = urllib.request.urlopen(req).read().decode('utf-8')
  resp = json.loads(resp_json)

  if not resp:
    return _error_response(request, err_exp.E_REGISTER_FAILED, "no response from models API")
  if resp['ok'] == False: # could be much more nuanced. makes web view handle errors
    return _error_response(request, err_exp.E_REGISTER_FAILED, resp)

  return _success_response(request, resp['resp'])


# fields = ['username', 'password', 'email_address','date_joined','is_active','f_name','l_name', 'bio']
项目:daas    作者:havron    | 项目源码 | 文件源码
def productdetails(request, drone_id): # /product-details/(?P<drone_id>\d+)
  if request.method != 'GET':
    return _error_response(request, err_exp.E_BAD_REQUEST, "must make GET request with drone_id")

  req = urllib.request.Request('http://models-api:8000/api/v1/drone/'+drone_id)
  resp_json = urllib.request.urlopen(req).read().decode('utf-8')
  resp = json.loads(resp_json)
  return _success_response(request, resp)
项目:daas    作者:havron    | 项目源码 | 文件源码
def listing(request, listing_id):
  if request.method != 'GET':
    return _error_response(request, err_exp.E_BAD_REQUEST, "must make a GET request with listing_id")
  req = urllib.request.Request('http://models-api:8000/api/v1/listing/'+listing_id)
  resp_json = urllib.request.urlopen(req).read().decode('utf-8')
  resp = json.loads(resp_json)
  return _success_response(request, resp)
项目:daas    作者:havron    | 项目源码 | 文件源码
def featured_items(request): # /shop/
  if request.method != 'GET':
    return _error_response(request, err_exp.E_BAD_REQUEST, "must make GET request")
  req  = urllib.request.Request('http://models-api:8000/api/v1/shop/')
  resp_json = urllib.request.urlopen(req).read().decode('utf-8')
  resp = json.loads(resp_json)
  return _success_response(request, resp)
项目:HydroNEXT    作者:OpenDataHack    | 项目源码 | 文件源码
def index(request):
    location=0
    if request.method == 'POST':
       existsLocalization = Localizacion.objects.filter(lugar_id = request.POST['lugar'] )
       if existsLocalization.count()==0:
         location= Localizacion.objects.create(lugar_id=request.POST['lugar']  , lugar_ds=request.POST['lugar']  )
         localizacion_id=location.id
         if location!=0:
            coordenadas = BuscarCoordenadas(location.lugar_ds)
            try:
                  coordenadasl = Coordenadas.objects.filter(local_ref = location.id)
                  coordenadasl.delete()
            except:
                  pass
            location.coordenadas_set.create(latitud=coordenadas.lat, longitud=coordenadas.lon, descripcion=coordenadas.ds)
            opcion= Option.objects.create(option_code=location.id ,option_type="lugares", option_text=coordenadas.ds )

    opcionesTemperatura = Option.objects.filter(option_type = "temperaturas")
    opcionesEcoRiverFlow = Option.objects.filter(option_type = "ecological river flow")
    opcionesMaximumFlow = Option.objects.filter(option_type = "Maximun flow")
    opcionesReservoirCapacity = Option.objects.filter(option_type = "Reservoir capacity")
    opcionesLugares = Option.objects.filter(option_type = "lugares")
    opcionesNetFalling = Option.objects.filter(option_type = "net falling height or head")
    opcionesNumberOfTurbines = Option.objects.filter(option_type = "Number of turbines")
    opcionesTypeOfTurbine = Option.objects.filter(option_type = "Type of turbines")
    anios = Option.objects.filter(option_type = "year")
    context = {
       'opcionesTemperatura': opcionesTemperatura,
       'opcionesEcoRiverFlow': opcionesEcoRiverFlow,
       'opcionesMaximumFlow': opcionesMaximumFlow,
       'opcionesReservoirCapacity': opcionesReservoirCapacity,
       'opcionesNetFalling': opcionesNetFalling,
       'opcionesNumberOfTurbines': opcionesNumberOfTurbines,
       'opcionesTypeOfTurbine': opcionesTypeOfTurbine,
       'opcionesLugares': opcionesLugares,
       'anios': anios,
    }
    return render(request, 'options/index.html', context)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_close(self):
        # Test close() by calling it here and then having it be called again
        # by the tearDown() method for the test
        self.returned_obj.close()
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def help_inputtype(self, given, test_type):
        """Helper method for testing different input types.

        'given' must lead to only the pairs:
            * 1st, 1
            * 2nd, 2
            * 3rd, 3

        Test cannot assume anything about order.  Docs make no guarantee and
        have possible dictionary input.

        """
        expect_somewhere = ["1st=1", "2nd=2", "3rd=3"]
        result = urllib.parse.urlencode(given)
        for expected in expect_somewhere:
            self.assertIn(expected, result,
                         "testing %s: %s not found in %s" %
                         (test_type, expected, result))
        self.assertEqual(result.count('&'), 2,
                         "testing %s: expected 2 '&'s; got %s" %
                         (test_type, result.count('&')))
        amp_location = result.index('&')
        on_amp_left = result[amp_location - 1]
        on_amp_right = result[amp_location + 1]
        self.assertTrue(on_amp_left.isdigit() and on_amp_right.isdigit(),
                     "testing %s: '&' not located in proper place in %s" %
                     (test_type, result))
        self.assertEqual(len(result), (5 * 3) + 2, #5 chars per thing and amps
                         "testing %s: "
                         "unexpected number of characters: %s != %s" %
                         (test_type, len(result), (5 * 3) + 2))
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_with_method_arg(self):
        Request = urllib.request.Request
        request = Request("http://www.python.org", method='HEAD')
        self.assertEqual(request.method, 'HEAD')
        self.assertEqual(request.get_method(), 'HEAD')
        request = Request("http://www.python.org", {}, method='HEAD')
        self.assertEqual(request.method, 'HEAD')
        self.assertEqual(request.get_method(), 'HEAD')
        request = Request("http://www.python.org", method='GET')
        self.assertEqual(request.get_method(), 'GET')
        request.method = 'HEAD'
        self.assertEqual(request.get_method(), 'HEAD')
项目:trunk-player    作者:ScanOC    | 项目源码 | 文件源码
def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(
            username=form.cleaned_data['username'],
            password=form.cleaned_data['password1'],
            email=form.cleaned_data['email']
            )
            username = form.cleaned_data['username']
            password = form.cleaned_data['password1']
            new_user = authenticate(username=username, password=password)
            if new_user is not None:
                if new_user.is_active:
                    stripe_actions.customers.create(user=new_user)
                    login(request, new_user)
                    return HttpResponseRedirect('/scan/default/')
                else:
                    # this would be weird to get here
                    return HttpResponseRedirect('/register/success/')
            else:
                return HttpResponseRedirect('/register/success/')
    else:
        form = RegistrationForm()

    return render(
    request,
    'registration/register.html',
    { 'form': form },
    )
项目:trunk-player    作者:ScanOC    | 项目源码 | 文件源码
def plans(request):
    token = None
    has_verified_email = False
    plans = None
    if request.method == 'POST':
        template = 'radio/subscribed.html'
        token = request.POST.get('stripeToken')
        plan = request.POST.get('plan')
        # See if this user already has a stripe account
        try:
            stripe_cust = stripe_models.Customer.objects.get(user=request.user)
        except ObjectDoesNotExist:
            stripe_actions.customers.create(user=request.user)
            stripe_cust = stripe_models.Customer.objects.get(user=request.user)
        try:
            stripe_info = stripe_actions.subscriptions.create(customer=stripe_cust, plan=plan, token=request.POST.get('stripeToken'))
        except stripe.CardError as e:
            template = 'radio/charge_failed.html'
            logger.error("Error with stripe user card{}".format(e))
            return render(request, template, {'error_msg': e })

        for t in request.POST:
          logger.error("{} {}".format(t, request.POST[t]))
    else:
        template = 'radio/plans.html'
        plans = StripePlanMatrix.objects.filter(order__lt=99).filter(active=True)

        # Check if users email address is verified
        verified_email = allauth_emailaddress.objects.filter(user=request.user, primary=True, verified=True)
        if verified_email:
            has_verified_email = True


    return render(request, template, {'token': token, 'verified_email': has_verified_email, 'plans': plans} )
项目:mpeds-coder    作者:MPEDS    | 项目源码 | 文件源码
def login():
    if request.method == 'GET':
        return render_template("login.html")

    username = request.form['username']
    password = request.form['password']
    reg_user = User.query.filter_by(username=username, password=password).first()
    if reg_user is None:
        flash("Username or password is invalid. Please try again.", "error")
        return redirect(url_for('login'))

    login_user(reg_user)
    return redirect(url_for('index'))
项目:mpeds-coder    作者:MPEDS    | 项目源码 | 文件源码
def prev(self, error_out=False):
        """Returns a :class:`Pagination` object for the previous page."""
        assert self.query is not None, 'a query object is required ' \
                                       'for this method to work'
        return paginate(self.query, self.page - 1, self.per_page, error_out)
项目:mpeds-coder    作者:MPEDS    | 项目源码 | 文件源码
def next(self, error_out=False):
        """Returns a :class:`Pagination` object for the next page."""
        assert self.query is not None, 'a query object is required ' \
                                       'for this method to work'
        return paginate(self.query, self.page + 1, self.per_page, error_out)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_close(self):
        # Test close() by calling it here and then having it be called again
        # by the tearDown() method for the test
        self.returned_obj.close()
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def help_inputtype(self, given, test_type):
        """Helper method for testing different input types.

        'given' must lead to only the pairs:
            * 1st, 1
            * 2nd, 2
            * 3rd, 3

        Test cannot assume anything about order.  Docs make no guarantee and
        have possible dictionary input.

        """
        expect_somewhere = ["1st=1", "2nd=2", "3rd=3"]
        result = urllib.parse.urlencode(given)
        for expected in expect_somewhere:
            self.assertIn(expected, result,
                         "testing %s: %s not found in %s" %
                         (test_type, expected, result))
        self.assertEqual(result.count('&'), 2,
                         "testing %s: expected 2 '&'s; got %s" %
                         (test_type, result.count('&')))
        amp_location = result.index('&')
        on_amp_left = result[amp_location - 1]
        on_amp_right = result[amp_location + 1]
        self.assertTrue(on_amp_left.isdigit() and on_amp_right.isdigit(),
                     "testing %s: '&' not located in proper place in %s" %
                     (test_type, result))
        self.assertEqual(len(result), (5 * 3) + 2, #5 chars per thing and amps
                         "testing %s: "
                         "unexpected number of characters: %s != %s" %
                         (test_type, len(result), (5 * 3) + 2))
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_with_method_arg(self):
        Request = urllib.request.Request
        request = Request("http://www.python.org", method='HEAD')
        self.assertEqual(request.method, 'HEAD')
        self.assertEqual(request.get_method(), 'HEAD')
        request = Request("http://www.python.org", {}, method='HEAD')
        self.assertEqual(request.method, 'HEAD')
        self.assertEqual(request.get_method(), 'HEAD')
        request = Request("http://www.python.org", method='GET')
        self.assertEqual(request.get_method(), 'GET')
        request.method = 'HEAD'
        self.assertEqual(request.get_method(), 'HEAD')
项目:ISeeNN    作者:sunshaoyan    | 项目源码 | 文件源码
def upload(request):
    if request.method == 'POST':
        form = ImageUploadForm(request.POST, request.FILES)
        if form.is_valid():
            return handle_uploaded_image(request)
        else:
            print("Not valid")
            return HttpResponseRedirect(reverse('search_web:index'))
    return HttpResponseRedirect(reverse('search_web:index'))
项目:FaceRecognitionAPI    作者:wassgha    | 项目源码 | 文件源码
def new(request):
    if request.method == "GET":
        if request.GET.get("username", None) is not None and request.GET.get("email", None) is not None:
            user = User.objects.create_user(request.GET.get("username", None), request.GET.get("email", None), '')
            user.first_name = request.GET.get("first_name", None)
            user.last_name = request.GET.get("last_name", None)
            user.save()
            training_folder = os.path.join(TRAINED_FACES_PATH, str(user.pk))
            if not os.path.exists(training_folder):
                os.makedirs(training_folder)
    return JsonResponse({"sucess": True})
项目:Github-Profile    作者:shubh1m    | 项目源码 | 文件源码
def index(request):
    BASE_URL = 'https://api.github.com/users/'
    form = SearchForm(request.POST or None)
    name = None
    details = ''
    status = ''
    photo = ''

    if request.method == 'POST':
        try:
            name = request.POST.get('search')

            #print(request.POST)
            url = BASE_URL + name
            r = requests.get(url)
            print(r.status_code)
            if(r.status_code == 404):
                status = 'User "' + name + '" does not exists.'
                name = None
            elif(r.status_code == 200):
                details = r.json()

                photo = details['avatar_url']
                name = details['name']

                details = (('Name', details['name']),
                            ('Bio', details['bio']),
                            ('UserID', details['login']),
                            ('Email', details['email']),
                            ('Company', details['company']),
                            ('Blog' , details['blog']),
                            ('Location' , details['location']),
                            ('Hireable' , details['hireable']),
                            ('Public Repos' , details['public_repos']),
                            ('Public Gists' , details['public_gists']),
                            ('Followers' , details['followers']),
                            ('Following' , details['following']),
                        )

                details = collections.OrderedDict(details)
            else:
                status = 'There is some error with your request. Please try again later.'

        except ConnectionError:
            status = "Connection Error!! Try again later"
        #except HTTPError:
        #    status = "Invalid HTTP Response!! Try again later"
        except:
            status = 'Error!! Try again later'

    context = {
        'form': form ,
        'name': name ,
        'status': status,
        'details': details,
        'photo': photo,
    }
    return render(request, 'index.html', context)
项目:django-g-recaptcha    作者:deltaskelta    | 项目源码 | 文件源码
def validate_captcha(view):
    """
    Decorator to validate a captcha, settings from django

    @validate_Captcha
    def a_view():
        ...
    """

    def wrap(request, *args, **kwargs):

        def failure_http():
            # Status 401 means that they are not authorized
            return render(request, 'captcha_fail.html', status=401)

        def failure_ajax():
            return HttpResponse(
                'There was a problem with the captcha, please try again', status=401)

        if request.method == 'POST':
            url = "https://www.google.com/recaptcha/api/siteverify"
            values = {
                'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
                'response': request.POST.get('g-recaptcha-response', None),
                'remoteip': request.META.get("REMOTE_ADDR", None),
            }

            data = urllib.parse.urlencode(values)
            req = urllib.request.Request(url, data)
            response = urllib.request.urlopen(req)
            result = json.loads(response.read())

            # result["success"] will be True on a success
            if result["success"]:
                return view(request, *args, **kwargs)
            elif request.is_ajax():
                return failure_ajax()
            else:
                return failure_http()

        return view(request, *args, **kwargs)
    wrap._original = view
    return wrap
项目:voiceai    作者:vidursatija    | 项目源码 | 文件源码
def hello():
    if request.method == 'GET':
        if request.args.get("hub.verify_token") == VERIFY_TOKEN:
            return request.args.get("hub.challenge")
        else:
            return 'Invalid verification token'

    if request.method == 'POST':
        output = request.get_json()
        for event in output['entry']:
            messaging = event['messaging']
            for x in messaging:
                if x.get('message'):
                    recipient_id = x['sender']['id']
                    if x['message'].get('text'):
                        message = x['message']['text']
                        msg =  AI.process_message(message)

                        bot.send_text_message(recipient_id, msg)
                    if x['message'].get('attachments'):
                        for att in x['message'].get('attachments'):
                            print(att['payload']['url'])
                            voice_url = urllib.request.urlopen(att['payload']['url'])
                            with open('voicemsg.aac', 'w+b') as f:
                                f.write(voice_url.read())
                            f.close()
                            aac_file = AudioSegment.from_file('voicemsg.aac', format='aac')
                            wav_handler = aac_file.export('rawmsg.wav', format='wav')
                            os.system("sox rawmsg.wav -r 16000 temp.wav")
                            wav_handler = AudioSegment.from_file('temp.wav', format='wav')
                            raw_handler = wav_handler.export('rawmsg.raw', format='raw')
                            decoder.start_utt()
                            stream = open('rawmsg.raw', 'rb')
                            #stream.seek(44)
                            while True:
                                buf = stream.read(1024)
                                if buf:
                                    decoder.process_raw(buf, False, False)
                                else:
                                    break
                            decoder.end_utt()
                            sentence = " ".join([seg.word for seg in decoder.seg()])
                            bot.send_text_message(recipient_id, sentence)
                            #bot.send_attachment_url(recipient_id, att['type'], att['payload']['url'])
                else:
                    pass
        return "Success"
项目:daas    作者:havron    | 项目源码 | 文件源码
def create_listing(request): # /create-listing
  if request.method != 'POST':  
    return _error_response(request, err_exp.E_BAD_REQUEST, "must make POST request")

  form = ListingForm(request.POST)
  if not form.is_valid():
    return _error_response(request, err_exp.E_FORM_INVALID, "listing form not correctly filled out")

  post_data = form.cleaned_data
  post_data['auth'] = request.POST['auth']
  post_data['last_checked_out'] = datetime.datetime.now()

  post_encoded = urllib.parse.urlencode(post_data).encode('utf-8')
  req = urllib.request.Request('http://models-api:8000/api/v1/drone/create/', data=post_encoded, method='POST')
  resp_json = urllib.request.urlopen(req).read().decode('utf-8')
  resp = json.loads(resp_json)

  if not resp:
    return _error_response(request, err_exp.E_REGISTER_FAILED, "no response from models API")
  if resp['ok'] == False: # could be much more nuanced. makes web view handle errors
    return _error_response(request, err_exp.E_REGISTER_FAILED, resp)

  post_data['_drone_key'] = resp['resp']['drone_id']
  post_data['time_posted'] = datetime.datetime.now()

  post_encoded = urllib.parse.urlencode(post_data).encode('utf-8')
  req = urllib.request.Request('http://models-api:8000/api/v1/listing/create/', data=post_encoded, method='POST')
  resp_json = urllib.request.urlopen(req).read().decode('utf-8')
  resp = json.loads(resp_json)

  if not resp:
    return _error_response(request, err_exp.E_REGISTER_FAILED, "no response from models API")
  if resp['ok'] == False: # could be much more nuanced. makes web view handle errors
    return _error_response(request, err_exp.E_REGISTER_FAILED, {'resp':resp})


  # add newly created listing to Kafka 
  # get listing 

  '''
  req = urllib.request.Request('http://models-api:8000/api/v1/listing/'+resp['resp']['listing_id'])
  resp_json = urllib.request.urlopen(req).read().decode('utf-8')
  resp1 = json.loads(resp_json)
  resp1['listing_id'] = resp['listing_id']
  '''

  # add to kafka
  producer = KafkaProducer(bootstrap_servers='kafka:9092')

  # need to pass dictionary object
  new_listing = resp['resp']['listing']
  producer.send('new-listings-topic', json.dumps(new_listing).encode('utf-8'))
  print(new_listing)

  return _success_response(request, resp['resp']['listing'])
项目:trunk-player    作者:ScanOC    | 项目源码 | 文件源码
def upgrade(request):
    if request.method == 'POST':
        form = PaymentForm(request.POST)
        if not form.is_valid():
            return render(
                request,
                'registration/upgrade.html',
                {'form': form},
            )

        try:
            plan = form.cleaned_data.get('plan_type')
            card_name = form.cleaned_data.get('cardholder_name')
            stripe_cust = stripe_models.Customer.objects.get(user=request.user)
            logger.error('Change plan to {} for customer {} Card Name {}'.format(plan, stripe_cust, card_name))
            stripe_info = stripe_actions.subscriptions.create(customer=stripe_cust, plan=plan, token=request.POST.get('stripeToken'))
        except stripe.InvalidRequestError as e:
            messages.error(request, "Error with stripe {}".format(e))
            logger.error("Error with stripe {}".format(e))
            return render(
                request,
                'registration/upgrade.html',
                {'form': form},
            )
        except stripe.CardError as e:
            messages.error(request, "<b>Error</b> Sorry there was an error with processing your card:<br>{}".format(e))
            logger.error("Error with stripe user card{}".format(e))
            return render(
                request,
                'registration/upgrade.html',
                {'form': form},
            )

        print('------ STRIPE DEBUG -----')
        pprint(stripe_info, sys.stderr)
        return render(
           request,
           'registration/upgrade_complete.html',
        )
    else:
        form = PaymentForm()
        return render(
           request,
           'registration/upgrade.html',
           {'form': form, },
        )