我们从Python开源项目中,提取了以下16个代码示例,用于说明如何使用urllib.request.POST。
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))
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
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'])
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")
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)
def recaptcha_verify(request, key): if not request.POST.get('g-recaptcha-response'): return False re_request = urllib.request.urlopen('https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}'.format(key, request.POST['g-recaptcha-response'])) jsond = json.loads(re_request.read().decode()) if not jsond['success']: return False return True
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']
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)
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 }, )
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} )
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'))
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)
def itinerary(request): template = get_template('itinerary.html') count = 0 attractions_data = [] try: delspot = request.POST['del_spot'] count = request.session['spot_num'] spots = [] delpoint = -1 for i in range(count): spots.append(str(i)) spots.append(request.session['add_spot'+str(i)]) print(spots) for i in range(count*2): if delspot == spots[i]: delpoint = spots[i-1] print(delpoint) del request.session['add_spot'+str(delpoint)] print('add_spot'+str(delpoint)) for i in range(count): if i > int(delpoint): request.session['add_spot'+str(i-1)] = spots[(i+1)*2-1] print(request.session['add_spot'+str(i-1)]) request.session['spot_num'] = count -1 print('spot'+request.session['spot_num']) except: pass try: count = request.session['spot_num'] spots = [] for i in range(count): spots.append(request.session['add_spot'+str(i)]) for i in range(count): attractions_data.append (Attractions.objects.get(at_name = spots[i])) except: alert = '????' html = template.render(locals()) return HttpResponse(html)
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'])
def mapa(request): type="" if '_caudal' in request.POST: type="_caudal" if '_energia' in request.POST: type="_energia" if '_periodos' in request.POST: type="_periodos" if '_forecast' in request.POST: type="_forecast" if type=="_forecast": return(ECMWF_dataRecover01.calculaCaudal(request)) elif 'localizacion_id' in request.POST: localizacion_id=request.POST['localizacion_id'] opcionesEcoRiverFlow=request.POST['opcionesEcoRiverFlow'] opcionesMaximumFlow=request.POST['opcionesMaximumFlow'] opcionesReservoirCapacity=request.POST['opcionesReservoirCapacity'] opcionesNetFalling=request.POST['opcionesNetFalling'] opcionesNumberOfTurbines=request.POST['opcionesNumberOfTurbines'] opcionesTypeOfTurbine=request.POST['opcionesTypeOfTurbine'] location = get_object_or_404(Localizacion, pk=localizacion_id) try: coordenadas = Coordenadas.objects.filter(local_ref = location.id) if type=="_caudal": return(readExcel.calculaCaudal(request, coordenadas[0].latitud, coordenadas[0].longitud,coordenadas[0].descripcion)) if type=="_energia": dataparameters =DataparametersClasss.DataparametersClasss () dataparameters.opcionesEcoRiverFlow=opcionesEcoRiverFlow dataparameters.opcionesMaximumFlow=opcionesMaximumFlow dataparameters.opcionesReservoirCapacity=opcionesReservoirCapacity dataparameters.opcionesNetFalling=opcionesNetFalling dataparameters.opcionesNumberOfTurbines=opcionesNumberOfTurbines dataparameters.opcionesTypeOfTurbine=opcionesTypeOfTurbine return(readExcel.calculaEnergia(request, coordenadas[0].latitud, coordenadas[0].longitud,coordenadas[0].descripcion,dataparameters)) if type=="_periodos": dataparameters =DataparametersClasss.DataparametersClasss () dataparameters.opcionesEcoRiverFlow=opcionesEcoRiverFlow dataparameters.opcionesMaximumFlow=opcionesMaximumFlow dataparameters.opcionesReservoirCapacity=opcionesReservoirCapacity dataparameters.opcionesNetFalling=opcionesNetFalling dataparameters.opcionesNumberOfTurbines=opcionesNumberOfTurbines dataparameters.opcionesTypeOfTurbine=opcionesTypeOfTurbine return(readExcel.calculaPeriodo(request, coordenadas[0].latitud, coordenadas[0].longitud,coordenadas[0].descripcion,dataparameters)) except: print("****errir**")
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, }, )