Project structure:

project --yadirectapi ----models.py ----urls.py ----views.py --templates ----yandex -----index.html -----yaapi.html 

In the project / yadirectapi / models.py file , the β€œcampaign” model is defined, and the function of requesting data via api. her, he can refer to the function get_companies .

I actually attach the project / yadirectapi / models.py code :

 from django.db import models import requests, json from requests.exceptions import ConnectionError from time import sleep import sys # Create your models here. class Company(models.Model): # Id ΠΊΠΎΠΌΠΏΠ°Π½ΠΈΠΈ, ΡƒΠ½ΠΈΠΊΠ°Π»ΡŒΠ½Ρ‹ΠΉ ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€ Id = models.IntegerField(primary_key=True) # НазваниС ΠΊΠΎΠΌΠΏΠ°Π½ΠΈΠΈ Name = models.CharField(max_length=255) # НазваниС ΠΊΠ»ΠΈΠ΅Π½Ρ‚Π° (Π΄ΠΎ 255 символов). Π—Π½Π°Ρ‡Π΅Π½ΠΈΠ΅ ΠΏΠΎ ΡƒΠΌΠΎΠ»Ρ‡Π°Π½ΠΈΡŽ β€” Π½Π°ΠΈΠΌΠ΅Π½ΠΎΠ²Π°Π½ΠΈΠ΅ ΠΈΠ· настроСк рСкламодатСля. ClientInfo = models.CharField(max_length=255) # Π”Π°Ρ‚Π° Π½Π°Ρ‡Π°Π»Π° ΠΏΠΎΠΊΠ°Π·ΠΎΠ² объявлСний Π² Ρ„ΠΎΡ€ΠΌΠ°Ρ‚Π΅ YYYY-MM-DD. Π”ΠΎΠ»ΠΆΠ½Π° Π±Ρ‹Ρ‚ΡŒ Π½Π΅ мСньшС Ρ‚Π΅ΠΊΡƒΡ‰Π΅ΠΉ Π΄Π°Ρ‚Ρ‹. StartDate = models.CharField(max_length=20) # Π”Π°Ρ‚Π° окончания ΠΏΠΎΠΊΠ°Π·ΠΎΠ² объявлСний Π² Ρ„ΠΎΡ€ΠΌΠ°Ρ‚Π΅ YYYY-MM-DD. # ΠŸΠΎΠΊΠ°Π·Ρ‹ объявлСний ΠΏΡ€Π΅ΠΊΡ€Π°Ρ‰Π°ΡŽΡ‚ΡΡ Π² 24:00 ΠΏΠΎ московскому Π²Ρ€Π΅ΠΌΠ΅Π½ΠΈ (нСзависимо ΠΎΡ‚ значСния ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€Π° TimeZone). EndDate = models.CharField(max_length=20) # Часовой пояс Π² мСстС нахоТдСния рСкламодатСля TimeZone = models.CharField(max_length=50) # Настройки Π΄Π½Π΅Π²Π½ΠΎΠ³ΠΎ Π±ΡŽΠ΄ΠΆΠ΅Ρ‚Π° ΠΊΠ°ΠΌΠΏΠ°Π½ΠΈΠΈ. # DailyBudget = models.CharField(max_length = 255) # Π’ΠΈΠΏ ΠΊΠ°ΠΌΠΏΠ°Π½ΠΈΠΈ Type = models.CharField(max_length=255) # Бтатус ΠΊΠ°ΠΌΠΏΠ°Π½ΠΈΠΈ Status = models.CharField(max_length=255) # БостояниС ΠΊΠ°ΠΌΠΏΠ°Π½ΠΈΠΈ State = models.CharField(max_length=255) # Бтатус ΠΎΠΏΠ»Π°Ρ‚Ρ‹ ΠΊΠ°ΠΌΠΏΠ°Π½ΠΈΠΈ StatusPayment = models.CharField(max_length=255) # ВСкстовоС пояснСниС статусу StatusClarification = models.CharField(max_length=255) # Бтатистика ΠΏΠΎΠΊΠ°Π·ΠΎΠ² ΠΈ ΠΊΠ»ΠΈΠΊΠΎΠ² Statistics = models.CharField(max_length=255) # Π’Π°Π»ΡŽΡ‚Π° ΠΊΠ°ΠΌΠΏΠ°Π½ΠΈΠΈ Currency = models.CharField(max_length=255) # ЀинансовыС ΠΏΠΎΠΊΠ°Π·Π°Ρ‚Π΅Π»ΠΈ ΠΊΠ°ΠΌΠΏΠ°Π½ΠΈΠΈ Funds = models.CharField(max_length=255) # Π”Π½Π΅Π²Π½ΠΎΠΉ Π±ΡŽΠ΄ΠΆΠ΅Ρ‚ ΠΊΠ°ΠΌΠΏΠ°Π½ΠΈΠΈ Π² Π²Π°Π»ΡŽΡ‚Π΅ рСкламодатСля, Π£ΠœΠΠžΠ–Π•ΠΠΠ«Π™ НА 1 000 000 Amount = models.FloatField() # Π Π΅ΠΆΠΈΠΌ ΠΏΠΎΠΊΠ°Π·Π° объявлСний Mode = models.CharField(max_length=255) # ΠšΠΎΠ»ΠΈΡ‡Π΅ΡΡ‚Π²ΠΎ ΠΏΠΎΠΊΠ°Π·ΠΎΠ² Impressions = models.FloatField() # ΠšΠΎΠ»ΠΈΡ‡Π΅ΡΡ‚Π²ΠΎ ΠΊΠ»ΠΈΠΊΠΎΠ² Clicks = models.FloatField() # Π‘ΡƒΠΌΠΌΠ° срСдств зачислСнных Π½Π° баланс ΠΊΠΎΠΌΠΏΠ°Π½ΠΈΠΈ Π·Π° врСмя Π΅Ρ‘ сущСствованиС Sum = models.FloatField() # Π’Π΅ΠΊΡƒΡ‰ΠΈΠΉ баланс ΠΊΠ°ΠΌΠΏΠ°Π½ΠΈΠΈ Balance = models.FloatField() # Π”Π΅Π½ΡŒΠ³ΠΈ Π·Π°Ρ‚Ρ€Π°Ρ‡Π΅Π½Π½Ρ‹Π΅ Π½Π° кампанию Π·Π° всё врСмя Π΅Ρ‘ сущСствования Spend = models.FloatField() def __str__(self): return self.Name def get_companies(): if sys.version_info < (3,): def u(x): try: return x.encode("utf8") except UnicodeDecodeError: return x else: def u(x): if type(x) == type(b''): return x.decode('utf8') else: return x CampaignsURL = 'https://api-sandbox.direct.yandex.com/json/v5/campaigns' token = '' # clientLogin = '' headers = {'Authorization': 'Bearer ' + token, # 'Client-Login': clientLogin, 'Accept-Language': 'ru', } body = {'method': 'get', 'params': {'SelectionCriteria': {}, 'FieldNames': ['Id', 'Name', 'ClientInfo', 'StartDate', 'EndDate', # 'TimeTargeting', 'TimeZone', 'DailyBudget', 'Type', 'Status', 'State', 'StatusPayment', 'StatusClarification', 'Statistics', 'Currency', 'Funds', # 'Amount', # 'Mode', # 'Impressions', # 'Clicks', # 'Sum', # 'Balance', # 'Spend', ] } } jsonBody = json.dumps(body, ensure_ascii=False).encode('utf8') try: result = requests.post(CampaignsURL, jsonBody, headers=headers) if result.status_code != 200 or result.json().get("error", False): print("ΠŸΡ€ΠΎΠΈΠ·ΠΎΡˆΠ»Π° ошибка ΠΏΡ€ΠΈ ΠΎΠ±Ρ€Π°Ρ‰Π΅Π½ΠΈΠΈ ΠΊ сСрвСру API Π”ΠΈΡ€Π΅ΠΊΡ‚Π°.") print("Код ошибки: {}".format(result.json()["error"]["error_code"])) print("ОписаниС ошибки: {}".format(u(result.json()["error"]["error_detail"]))) print("RequestId: {}".format(result.headers.get("RequestId", False))) else: print("RequestId: {}".format(result.headers.get("RequestId", False))) print("Π˜Π½Ρ„ΠΎΡ€ΠΌΠ°Ρ†ΠΈΡ ΠΎ Π±Π°Π»Π»Π°Ρ…: {}".format(result.headers.get("Units", False))) # Π’Ρ‹Π²ΠΎΠ΄ списка ΠΊΠ°ΠΌΠΏΠ°Π½ΠΈΠΉ AHTUNG!!! for campaign in result.json()["result"]["Campaigns"]: print("РСкламная кампания: {} β„–{}".format(u(campaign['Name']), campaign['Id'])) if result.json()['result'].get('LimitedBy', False): # Если ΠΎΡ‚Π²Π΅Ρ‚ содСрТит ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€ LimitedBy, Π·Π½Π°Ρ‡ΠΈΡ‚, Π±Ρ‹Π»ΠΈ ΠΏΠΎΠ»ΡƒΡ‡Π΅Π½Ρ‹ Π½Π΅ всС доступныС ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Ρ‹. # Π’ этом случаС слСдуСт Π²Ρ‹ΠΏΠΎΠ»Π½ΠΈΡ‚ΡŒ Π΄ΠΎΠΏΠΎΠ»Π½ΠΈΡ‚Π΅Π»ΡŒΠ½Ρ‹Π΅ запросы для получСния всСх ΠΎΠ±ΡŠΠ΅ΠΊΡ‚ΠΎΠ². # ΠŸΠΎΠ΄Ρ€ΠΎΠ±Π½ΠΎΠ΅ описаниС постраничной Π²Ρ‹Π±ΠΎΡ€ΠΊΠΈ - # https://tech.yandex.ru/direct/doc/dg/best-practice/get-docpage/#page print("ΠŸΠΎΠ»ΡƒΡ‡Π΅Π½Ρ‹ Π½Π΅ всС доступныС ΠΎΠ±ΡŠΠ΅ΠΊΡ‚Ρ‹.") except requests.exceptions.ConnectionError: # Π’ Π΄Π°Π½Π½ΠΎΠΌ случаС ΠΌΡ‹ Ρ€Π΅ΠΊΠΎΠΌΠ΅Π½Π΄ΡƒΠ΅ΠΌ ΠΏΠΎΠ²Ρ‚ΠΎΡ€ΠΈΡ‚ΡŒ запрос ΠΏΠΎΠ·Π΄Π½Π΅Π΅ print("ΠŸΡ€ΠΎΠΈΠ·ΠΎΡˆΠ»Π° ошибка соСдинСния с сСрвСром API.") # Если Π²ΠΎΠ·Π½ΠΈΠΊΠ»Π° какая-Π»ΠΈΠ±ΠΎ другая ошибка except: # Π’ Π΄Π°Π½Π½ΠΎΠΌ случаС ΠΌΡ‹ Ρ€Π΅ΠΊΠΎΠΌΠ΅Π½Π΄ΡƒΠ΅ΠΌ ΠΏΡ€ΠΎΠ°Π½Π°Π»ΠΈΠ·ΠΈΡ€ΠΎΠ²Π°Ρ‚ΡŒ дСйствия прилоТСния print("ΠŸΡ€ΠΎΠΈΠ·ΠΎΡˆΠ»Π° нСпрСдвидСнная ошибка.") return result 

The synch function is defined in the project / yadirectapi / views.py synch , as well as the index and yaapi drawing functions. Here I have some concerns about the work of the synch function synch perhaps the error is somewhere in it, specifically in the update_or_create method.

I attach the project / yadirectapi / views.py file :

 import sys from django.http import HttpResponseRedirect from django.shortcuts import render from .models import Company import requests, json def index(request): return render(request, 'yandex/index.html') def yaapi(request): return render(request, 'yandex/yaapi.html') def synch(request): if request.method == "POST": if sys.version_info < (3,): def u(x): try: return x.encode("utf8") except UnicodeDecodeError: return x else: def u(x): if type(x) == type(b''): return x.decode('utf8') else: return x result = Company.get_companies() for campaign in result.json()['result']['Campaigns']: company, created = Company.objects.update_or_create( Id=u(campaign['Id']), Name=u(campaign['Name']), ClientInfo=u(campaign['ClientInfo']), StartDate=u(campaign['StartDate']), EndDate=u(campaign['EndDate']), TimeZone=u(campaign['TimeZone']), Type=u(campaign['Type']), Status=u(campaign['Status']), State=u(campaign['State']), StatusPayment=u(campaign['StatusPayment']), StatusClarification=u(campaign['StatusClarification']), Statistics=u(campaign['Statistics']), Currency=u(campaign['Currency']), Funds=u(campaign['Funds']), Amount=u(campaign['DailyBudget']['Amount']), Mode=u(campaign['DailyBudget']['Mode']), Impressions=u(campaign['Statistics']['Impressions']), Clicks=u(campaign['Statistics']['Clicks']), Sum=u(campaign['Funds']['CampaignFunds']['Sum']), Balance=u(campaign['Funds']['CampaignFunds']['Balance']), Spend=u(campaign['Funds']['CampaignFunds']['Spend']), defaults={"Name": Name, "ClientInfo": ClientInfo, "StartDate": StartDate, "EndDate": EndDate, "TimeZone": TimeZone, "Type": Type, "Status": Status, "State": State, "StatusPayment": StatusPayment, "StatusClarification": StatusClarification, "Statistics": Statistics, "Currency": Currency, "Funds": Funds, "Amount": Amount, "Mode": Mode, "Impressions": Impressions, "Clicks": Clicks, "Sum": Sum, "Balance": Balance, "Spend": Spend, }) return HttpResponseRedirect('/') 

Well, the remaining project / yadirectapi / urls.py files :

 from django.urls import path from . import views urlpatterns = [ path(r'', views.index), path(r'ya_api/', views.yaapi, name='yaapi'), path(r'synch/', views.synch), ] 

And the project / templates / yandex / yaapi.html file :

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="POST" action={{yadirectapi.views.synch}}> {# ΠŸΡ€ΠΎΠ±ΠΎΠ²Π°Π» Π΅Ρ‰Ρ‘ Π²ΠΎΡ‚ Ρ‚Π°ΠΊ: <form method="POST" action="synch/"> #} {% csrf_token %} <input type='submit' value="synch"> </form> <a href="/">index</a> </body> </html> 

Well, actually the console output:

 [05/Nov/2018 17:27:43] "POST /ya_api/synch/ HTTP/1.1" 404 2447 Not Found: /ya_api/synch/ 

And the output on the website by clicking on the button:

 Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/ya_api/synch Using the URLconf defined in erpmod.urls, Django tried these URL patterns, in this order: admin/ ya_api/ [name='yaapi'] synch/ The current path, ya_api/synch, didn't match any of these. 

    0