def post(self, request, *args, **kwargs): serializer = HistorySerializer(data=self.request.data) if serializer.is_valid(): user = self.request.user document_id = self.request.data['documentId'] try: color = True if self.request.data['color'] == 'true' else False except: color = False try: double_sided = True if self.request.data['doubleSided'] == 'true' else False # fix this, dont need to set value this way except: double_sided = False file = File.objects.get(id=document_id) npages = file.npages date = datetime.now() # We use the npages of a document to retrieve the amount to pay. topay = math.ceil(npages / 2) * 0.4 if double_sided else npages * 0.4 # they only have to pay for sheet, so if they print double sided, a sheet is 2 sided. History.objects.create( user=user, documentId=file, color=color, npages=npages, amount=topay, doubleSided=double_sided, date=date, ) #file.create() if color: # mail(file.name, file.file.read()) print("color") pass else: from webplatform.settings_secret import PRINT_SERVER, PRINT_PASSWORD, PRINT_USERNAME post_data = [{ "username": PRINT_USERNAME, "password": PRINT_PASSWORD, "url": str(file.file.url), "filename": str(file.name), }] try: print(PRINT_SERVER) requests.post(PRINT_SERVER, json=post_data) except Exception as e: return Response({'response': str(e)}, status=status.HTTP_400_BAD_REQUEST) return Response({'response': 'Printing document'}, status=status.HTTP_200_OK) return Response({'response': 'Incorrect data'}, status=status.HTTP_406_NOT_ACCEPTABLE)
def send_email(messaging_object): url = MESSAGING_SERVICE_URL + "" + MESSAGING_EMAIL_ENDPOINT post_data = messaging_object response = requests.post(url=url, data=post_data) # extracting data in json format return response.content.json()
def get_branch(request): if request.method == 'POST': drop_m = { "Table_name": "gal_mst_tbranch", "Column_1": "branch_gid,branch_name", "Column_2": "", "Where_Common": "branch", "Where_Primary": "", "Primary_Value": "", "Order_by": "name" } drop_table = {"data": drop_m} obj = view_master.All_Tables_Values_Get() obj.actn = 'FABRANCH' obj.entity_gid = 1 params = {'Action': obj.actn, 'Entity_Gid': obj.entity_gid} headers = { "content-type": "application/json", "Authorization": "" + token + "" } datas = json.dumps(drop_table.get('data')) resp = requests.post("" + ip + "/All_Tables_Values_Get", params=params, data=datas, headers=headers, verify=False) response = resp.content.decode("utf-8") return HttpResponse(response)
def drop_branch(request): if request.method == 'POST': drop_b = { "Table_name": "ap_mst_tcategory", "Column_1": "category_gid,category_name", "Column_2": "", "Where_Common": "category", "Where_Primary": "", "Primary_Value": "", "Order_by": "name" } drop_tables = {"data": drop_b} obj = view_sales.SalesOrder_Register() obj.action = 'Debit' obj.entity_gid = 1 params = {'Action': obj.action, 'Entity_Gid': obj.entity_gid} headers = { "content-type": "application/json", "Authorization": "" + token + "" } datas = json.dumps(drop_tables.get('data')) resp = requests.post("" + ip + "/All_Tables_Values_Get", params=params, data=datas, headers=headers, verify=False) response = resp.content.decode("utf-8") return HttpResponse(response)
def sale_make(request): if request.method == 'POST': jsondata = json.loads(request.body.decode('utf-8')) obj = view_fa.FA_Asset_Make() obj.act = jsondata.get('params').get('Action') obj.grp = jsondata.get('params').get('Group') obj.channel = jsondata.get('params').get('Channel') obj.so_header_date = jsondata.get('params').get('So_Header_date') obj.entity = jsondata.get('params').get('Employee_Gid') params = { "Action": obj.act, "Group": obj.grp, "Employee_Gid": obj.entity, "Channel": obj.channel, "So_Header_date": obj.so_header_date } headers = { "content-type": "application/json", "Authorization": "" + token + "" } datas = json.dumps(jsondata.get('params').get('json')) resp = requests.post("" + ip + "/FA_SALE", params=params, data=datas, headers=headers, verify=False) response = resp.content.decode("utf-8") return HttpResponse(response)
def fin_year(request): if request.method == 'POST': jsondata = json.loads(request.body.decode('utf-8')) obj = view_fa.FinYear() obj.act = jsondata.get('params').get('Action') obj.grp = jsondata.get('params').get('Group') obj.typ = jsondata.get('params').get('Type') obj.sub = jsondata.get('params').get('Sub_Type') obj.entity = jsondata.get('params').get('Employee_Gid') params = { "Action": obj.act, "Group": obj.grp, "Type": obj.typ, "Sub_Type": obj.sub, "Employee_Gid": obj.entity } headers = { "content-type": "application/json", "Authorization": "" + token + "" } datas = json.dumps(jsondata.get('params').get('json')) resp = requests.post("" + ip + "/FIN_YEAR", params=params, data=datas, headers=headers, verify=False) response = resp.content.decode("utf-8") return HttpResponse(response)
def get_token(): url = 'http://192.168.10.12:8000/login' login_data = {'username': '******', 'password': '******', 'eauth': 'pam'} headers = {'Accept': 'application/json'} res = requests.post(url, headers=headers, data=login_data) token = res.json()['return'][0]['token'] return token
def saltCmd(ip, fun, *args, **kwargs): token = get_token() url = "http://192.168.10.12:8000" headers = {'Accept': 'application/json', "X-Auth-Token": token} res = requests.post(url, headers=headers, json= \ {'client': 'local', 'tgt': ip, 'fun': fun, 'arg': list(args), 'kwarg': kwargs}) response = res.json()['return'] return response
def shorten_url(url): post_url = 'https://www.googleapis.com/urlshortener/v1/url?key={}'.format( 'AIzaSyDBKox6Urc8SUwws9mXT9zJFaDbQlN0FL8') payload = {'longUrl': url} headers = {'content-type': 'application/json'} r = requests.post(post_url, data=json.dumps(payload), headers=headers) url_dict = r.json() return url_dict['id']
def send_sms(self, code, mobile): params = { 'api_key': self.api_key, 'mobile': mobile, 'text': '【乐搜网】您的手机验证码是{code}。本条信息无需回复'.format(code=code) } response = requests.post(self.single_send_url, params) result = json.loads(response.text) print(result)
def authorize(request): api_client = APIClient(app_id="57j65z6aezdxuocajwwegvkyx", app_secret="du2z08iomhm6remzvzyhk8bz9") response_body = { "client_id": api_client.app_id, "name": "alexandra", "email_address": request.data.get('email'), "provider": "outlook", "settings": { "username": request.data.get('email'), "password": request.data.get('password'), } } nylas_authorize_resp = requests.post( "https://api.nylas.com/connect/authorize", json=response_body) print(nylas_authorize_resp.json()) # nylas_code = nylas_authorize_resp.json()["code"] nylas_code = 'd80cOfUCvwW-teOcAtvh' state = 'WM6D' nylas_token_data = { "client_id": api_client.app_id, "client_secret": api_client.app_secret, "code": nylas_code, "state": state } nylas_token_resp = requests.post("https://api.nylas.com/connect/token", json=nylas_token_data) if not nylas_token_resp.ok: message = nylas_token_resp.json()["message"] return Response('Bad Request') nylas_access_token = nylas_token_resp.json()["access_token"] data = {"code": nylas_code, "access_token": nylas_access_token} return Response(data)
def test_forms(self): post_url = 'http://127.0.0.1:8000/api/dish/dishes/' files = {"image": open("3.png", 'rb')} form_data = { 'name_dish': 'Шашлык', "nutrition_value": "250", "value": "600" } r = requests.post(post_url, data=form_data, files=files) form = AddDish(data=form_data) self.assertTrue(form.is_valid()) self.assertEqual(r.status_code, 200)
def proxy_to(request, path, target_url): url = '%s%s' % (target_url, path) headers = { } if request.method == 'GET': proxied_response = requests.get(url, headers=headers) elif request.method == 'POST': proxied_response = requests.post(url, data=request.body, headers=headers) elif request.method == 'PUT': proxied_response = requests.put(url, data=request.body, headers=headers) elif request.method == 'DELETE': proxied_response = requests.delete(url, data=request.body, headers=headers) return HttpResponse(proxied_response)
def wrap(request, *args, **kwargs): request.recaptcha_is_valid = None if request.method == 'POST': recaptcha_response = request.POST.get('g-recaptcha-response') data = { 'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY, 'response': recaptcha_response } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) result = r.json() if result['success']: request.recaptcha_is_valid = True else: request.recaptcha_is_valid = False messages.error(request, 'Invalid reCAPTCHA. Please try again.') return function(request, *args, **kwargs)
def oauth_redirect(request: HttpRequest): code = request.GET.get("code") print(code) data = { "client_id": config["clientID"], "client_secret": config["clientSecret"], "grant_type": "authorization_code", "code": code, "redirect_uri": "http://localhost:8000/oauth/redirect", "scope": "identify" } headers = { 'Content Type': 'application/x-www-form-urlencoded' } response = requests.post("https://discord.com/api/oauth2/token", data=data, headers=headers) print(response.json()) return JsonResponse({"msg": "hi"})
def register(request): if request.method == "POST": user = User() user.username = request.POST['email'] user.email = request.POST['email'] user.set_password(request.POST['password']) user.save() newMember = unapprovedMember() newMember.user = user newMember.save() return render(request, 'alumni/homepage.html', []) elif request.method == "GET": initialState = "10" if request.GET['state'] != initialState: return HttpResponseBadRequest( "State does not match, likely a CSRF attack.") if not request.GET['code']: return HttpResponseBadRequest("User rejected Authorization") post_data = { 'code': request.GET['code'], 'grant_type': 'authorization_code', 'redirect_uri': 'Same as before', #TODO: fix these params 'client_id': '775rr0dby015ec', 'client_secret': '2w7UohNJkA5NRyyI', } response = requests.post('https://linkedin.com/oauth/v2/accessToken', data=post_data) content = json.loads(response.content) profileInfo = alumni.utils.requestingLinkedinProfileInf( content['access_token']) user = User() user.username = profileInfo['public-profile-url'] user.set_password(profileInfo['site-standard-profile-request'] + profileInfo['id']) user.save() #TODO: fill in new member with profile info newMember = unapprovedMember() newMember.user = user newMember.save() return render(request, 'alumni/homepage.html', []) else: context = {} context['error_message'] = "Registration failed due to a bad Request." return render(request, 'alumni/error_page.html', context)
def fa_category_get(request): if request.method == 'POST': jsondata = json.loads(request.body.decode('utf-8')) obj = view_fa.FA_Category() obj.grp = jsondata.get('params').get('Group') obj.typ = jsondata.get('params').get('Type') obj.sub = jsondata.get('params').get('Sub_Type') params = {"Group": obj.grp, "Type": obj.typ, "Sub_Type": obj.sub} headers = { "content-type": "application/json", "Authorization": "" + token + "" } datas = json.dumps(jsondata.get('params').get('json')) resp = requests.post("" + ip + "/FA_CATEGORY", params=params, data=datas, headers=headers, verify=False) response = resp.content.decode("utf-8") return HttpResponse(response)
def is_match(self, comment, result): global last_api_call_timestamp match = False # Gather info for API call headers = {"Content-Type": "application/json"} payload = json.dumps({"text": comment.body}) auth = HTTPBasicAuth(credentials["username"], credentials["password"]) # Rate limit api calls since_last_api_call = time.time() - last_api_call_timestamp if since_last_api_call < API_RATE_LIMIT: remaining = API_RATE_LIMIT - since_last_api_call time.sleep(remaining) # Send API call last_api_call_timestamp = time.time() response = requests.post(credentials["url"], data=payload, headers=headers, auth=auth) # Parse results of tone analysis if response.status_code == 200: # Get scores result = response.json() scores = result["children"] # Get emotion scores emotion_scores = None for score in scores: if score["id"] == "emotion_tone": emotion_scores = score # Get anger and negative scores in particular anger = [emotion for emotion in emotion_scores["children"] if emotion["id"] == "Anger"][0] negative = [emotion for emotion in emotion_scores["children"] if emotion["id"] == "Negative"][0] # If found match, record it match = anger["normalized_score"] >= ANGER_THRESHOLD and negative["normalized_score"] >= NEGATIVE_THRESHOLD return match
def distancia(request): # Verifica si hay un parámetro codigo en la petición GET if 'codigo' and 'longitud' and 'latitud' and 'terreno' and 'area' in request.GET: codigo = request.GET['codigo'] longitud = request.GET['longitud'] latitud = request.GET['latitud'] terreno = request.GET['terreno'] area = request.GET['area'] # Verifica si el area no esta vacio if codigo and longitud and latitud and terreno and area: # Crea el json para realizar la petición POST al Web Service args = {'codigo': codigo, 'longitud': longitud, 'latitud': latitud, 'terreno': terreno, 'area': area} response = requests.post('http://pi1-eafit-fperezm1.azurewebsites.net/distancias/', args) # Convierte la respuesta en JSON measure_json = response.json() # Realiza una petición GET al Web Services response = requests.get('http://pi1-eafit-fperezm1.azurewebsites.net/distancias/') # Convierte la respuesta en JSON distancia = response.json() # Rederiza la respuesta en el template measure return render(request, "distancia/distancia.html", {'distancias': distancia})
def get(self, request, *args, **kwargs): code = request.args.get('code') state = request.args.get('state') business = Business.objects.get_by_token(token=state) if not business: return HttpResponse(status=404) data = { "grant_type": "authorization_code", "client_id": STRIPE_CLIENTE_ID, "client_secret": STRIPE_API_KEY, "code": code } # Make /oauth/token endpoint POST request url = settings.STRIPE_OAUTH_SITE + settings.STRIPE_TOKEN_URI resp = requests.post(url, params=data) access_token = resp.json().get('access_token') stripe_user_id = resp.json().get('stripe_user_id') stripe_publishable_key = resp.json().get('stripe_publishable_key') try: with transaction.atomic(): account = create_account( access_token=access_token, stripe_user_id=stripe_user_id, stripe_publishable_key=stripe_publishable_key) business.set_account(account=account) except: return HttpResponse(status=500) return HttpResponseRedirect(redirect_to=reverse('beta_home'))
def upload_file(request): assert_file = request.FILES.get("file", None) wb = xlrd.open_workbook(filename=None, file_contents=assert_file.read()) # 读取机房等级信息 idc_level_table = wb.sheets()[0] for i in range(1, idc_level_table.nrows): row = idc_level_table.row_values(i) if len(IDCLevel.objects.filter(name=row[0])) == 0: IDCLevel(name=row[0], comment=row[1]).save() # 读取ISP信息 isp_table = wb.sheets()[1] for i in range(1, isp_table.nrows): row = isp_table.row_values(i) if len(ISP.objects.filter(name=row[0])) == 0: ISP(name=row[0]).save() # 读取机房信息 idc_table = wb.sheets()[2] for i in range(1, idc_table.nrows): row = idc_table.row_values(i) if len(IDC.objects.filter(name=row[0])) == 0: try: IDC(name=row[0], bandwidth=row[1], phone=row[2], linkman=row[3], address=row[4], concat_email=row[5], network=row[6], operator=ISP.objects.get(name=row[7]), type=IDCLevel.objects.get(name=row[8]), comment=row[9]).save() except Exception as e: pass # 机柜 for i in range(1, wb.sheets()[3].nrows): row = wb.sheets()[3].row_values(i) if len(Cabinet.objects.filter(name=row[1])) == 0: try: Cabinet(idc=IDC.objects.get(name=row[0]), name=row[1]).save() except Exception as e: pass # 机架 for i in range(1, wb.sheets()[4].nrows): row = wb.sheets()[4].row_values(i) if len(Rack.objects.filter(name=row[1])) == 0: try: Rack(idc=IDC.objects.get(name=row[0]), cabinet=Cabinet.objects.get(name=row[1]), name=row[2]).save() except Exception as e: pass # 主机组 for i in range(1, wb.sheets()[5].nrows): row = wb.sheets()[5].row_values(i) if len(HostGroup.objects.filter(name=row[1])) != 0: continue try: if row[0] == "": HostGroup(name=row[1]).save() else: HostGroup(parent=HostGroup.objects.get(name=row[0]), name=row[1]).save() except Exception as e: pass # 主机 for i in range(1, wb.sheets()[6].nrows): row = wb.sheets()[6].row_values(i) try: enable_sudo = False if row[7] != '0': enable_sudo = True except Exception as e: pass if len(Host.objects.filter(host_name=row[1])) != 0: continue if row[1] != '' and Host.objects.filter(host=row[1]).count() == 0: try: host = Host(host=row[1], enable_ssh=True, ssh_username=row[5], ssh_password=row[6], enable_sudo=enable_sudo) if str(row[0]) != '' and HostGroup.objects.filter( name=str(row[0])).count() != 0: host.host_group = HostGroup.objects.get(name=str(row[0])) if str(row[3]) != '' and IDC.objects.filter( name=str(row[3])).count() != 0: host.idc = IDC.objects.get(name=str(row[3])) if str(row[4]) != '' and Cabinet.objects.filter( name=str(row[4])).count() != 0: host.cabinet = Cabinet.objects.get(name=str(row[4])) if str(row[5]) != '' and Rack.objects.filter( name=str(row[5])).count() != 0: host.rack = Rack.objects.get(name=str(row[5])) host.save() except Exception as e: print('导入主机失败', e) # 更新一遍Rouster信息 hosts = Host.objects.all() rosterString = "" for host in hosts: if host.enable_ssh is True: rosterString += """ %s: host: %s user: %s passwd: %s sudo: %s tty: True """ % (host.host, host.host, host.ssh_username, host.ssh_password, host.enable_ssh) if SALT_CONN_TYPE == 'http': requests.post(SALT_HTTP_URL + '/rouster', data={'content': rosterString}) else: with open('/etc/salt/roster', 'w') as content: content.write(rosterString) return HttpResponse("")
def orderproduct(request): category = Category.objects.all() current_user = request.user shopcart = ShopCart.objects.filter(user_id=current_user.id) total = 0 for rs in shopcart: if rs.product.variant == 'None': total += rs.product.price * rs.quantity else: total += rs.variant.price * rs.quantity transport = 0 for rs in shopcart: transport += rs.product.transportation * rs.quantity final_total = total + transport amount = 0 for rs in shopcart: amount += rs.quantity if request.method == 'POST': # if there is a post form = OrderForm(request.POST) # return HttpResponse(request.POST.items()) if form.is_valid(): # Send Credit card to bank, If the bank responds ok, continue, if not, show the error req_data = { "merchant_id": MERCHANT, "amount": amount, "callback_url": CallbackURL, "description": description, "metadata": {"mobile": mobile, "email": email} } req_header = {"accept": "application/json", "content-type": "application/json'"} req = requests.post(url=ZP_API_REQUEST, data=json.dumps( req_data), headers=req_header) authority = req.json()['data']['authority'] if len(req.json()['errors']) == 0: return redirect(ZP_API_STARTPAY.format(authority=authority)) else: e_code = req.json()['errors']['code'] e_message = req.json()['errors']['message'] return HttpResponse(f"Error code: {e_code}, Error Message: {e_message}") # .............. data = Order() data.first_name = form.cleaned_data['first_name'] # get product quantity from form data.last_name = form.cleaned_data['last_name'] data.address = form.cleaned_data['address'] data.city = form.cleaned_data['city'] data.phone = form.cleaned_data['phone'] data.user_id = current_user.id data.total = total data.ip = request.META.get('REMOTE_ADDR') ordercode = get_random_string(5).upper() # random cod data.code = ordercode data.save() # for rs in shopcart: detail = OrderProduct() detail.order_id = data.id detail.product_id = rs.product_id detail.user_id = current_user.id detail.quantity = rs.quantity if rs.product.variant == 'None': detail.price = rs.product.price else: detail.price = rs.variant.price detail.variant_id = rs.variant_id detail.amount = rs.amount detail.save() # ***Reduce quantity of sold product from Amount of Product if rs.product.variant == 'None': product = Product.objects.get(id=rs.product_id) product.amount -= rs.quantity product.save() else: variant = Variants.objects.get(id=rs.product_id) variant.quantity -= rs.quantity variant.save() # ************ <> ***************** setting = Setting.objects.get(pk=1) ShopCart.objects.filter(user_id=current_user.id).delete() # Clear & Delete shopcart request.session['cart_items'] = 0 messages.success(request, "خرید شما با موفقیت انجام شد") return render(request, 'Order_Completed.html', {'ordercode': ordercode, 'category': category, 'setting': setting, 'amount':amount}) else: messages.warning(request, form.errors) return HttpResponseRedirect("/order/orderproduct") form = OrderForm() profile = UserProfile.objects.get(user_id=current_user.id) setting = Setting.objects.get(pk=1) context = {'shopcart': shopcart, 'category': category, 'total': total, 'form': form, 'profile': profile, 'transport': transport, 'final_total': final_total, 'setting': setting, 'amount':amount } return render(request, 'Order_Form.html', context)