【问题标题】:I'm getting this JSONDecodeError at /vaccine/handle vaccine slots/ on heroku server but on my local server its working fine我在 heroku 服务器上的 /vaccine/handle 疫苗插槽 / 收到这个 JSONDecodeError 但在我的本地服务器上它工作正常
【发布时间】:2021-08-09 17:36:15
【问题描述】:

Heroku 日志

2021-05-20T09:48:41.906814+00:00 app[web.1]: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
2021-05-20T09:48:41.907973+00:00 app[web.1]: 10.5.245.135 - - [20/May/2021:09:48:41 +0000] "POST /vaccine/handle_vaccine_slots/ HTTP/1.1" 500 82617 "https://systemofreckoning.herokuapp.com/vaccine/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36"
2021-05-20T09:48:41.909232+00:00 heroku[router]: at=info method=POST path="/vaccine/handle_vaccine_slots/" host=systemofreckoning.herokuapp.com request_id=d4a0b644-a44b-435f-963a-6cf8eaa9a5da fwd="103.88.217.153" dyno=web.1 connect=1ms service=141ms status=500 bytes=82877 protocol=https
2021-05-20T09:49:27.945441+00:00 app[web.1]: 10.97.195.7 - - [20/May/2021:09:49:27 +0000] "GET /logout/ HTTP/1.1" 302 0 "-" "Mozilla/5.0 (compatible; proximic; +https://www.comscore.com/Web-Crawler)"
2021-05-20T09:49:27.946900+00:00 heroku[router]: at=info method=GET path="/logout/" host=systemofreckoning.herokuapp.com request_id=fdeb198f-21c1-4d20-913d-ee93134c5b07 fwd="18.232.161.22" dyno=web.1 connect=0ms service=3ms status=302 bytes=395 protocol=https
2021-05-20T09:49:27.962588+00:00 app[web.1]: 10.97.195.7 - - [20/May/2021:09:49:27 +0000] "GET /accounts/login/ HTTP/1.1" 200 7748 "-" "Mozilla/5.0 (compatible; proximic; +https://www.comscore.com/Web-Crawler)"
2021-05-20T09:49:27.964058+00:00 heroku[router]: at=info method=GET path="/accounts/login/" host=systemofreckoning.herokuapp.com request_id=3fe99047-99a3-4d96-ad1f-087146838825 fwd="18.232.161.22" dyno=web.1 connect=0ms service=14ms status=200 bytes=8282 protocol=https
2021-05-20T09:50:05.878286+00:00 heroku[run.9390]: Client connection closed. Sending SIGHUP to all processes
2021-05-20T09:50:06.436547+00:00 heroku[run.9390]: Process exited with status 129
2021-05-20T09:50:06.537160+00:00 heroku[run.9390]: State changed from up to complete
2021-05-20T09:50:36.900551+00:00 heroku[router]: at=info method=POST path="/vaccine/handle_vaccine_slots/" host=systemofreckoning.herokuapp.com request_id=84aeeb06-fb0c-4802-910b-fc05d58fda52 fwd="103.88.217.153" dyno=web.1 connect=0ms service=126ms status=500 bytes=82891 protocol=https
2021-05-20T09:50:36.895526+00:00 app[web.1]: Internal Server Error: /vaccine/handle_vaccine_slots/
2021-05-20T09:50:36.895536+00:00 app[web.1]: Traceback (most recent call last):
2021-05-20T09:50:36.895537+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
2021-05-20T09:50:36.895537+00:00 app[web.1]:     response = get_response(request)
2021-05-20T09:50:36.895547+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
2021-05-20T09:50:36.895547+00:00 app[web.1]:     response = wrapped_callback(request, *callback_args, **callback_kwargs)
2021-05-20T09:50:36.895548+00:00 app[web.1]:   File "/app/vaccine/views.py", line 51, in handleVaccine
2021-05-20T09:50:36.895548+00:00 app[web.1]:     states = response.json()["states"]
2021-05-20T09:50:36.895549+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.9/site-packages/requests/models.py", line 897, in json
2021-05-20T09:50:36.895549+00:00 app[web.1]:     return complexjson.loads(self.text, **kwargs)
2021-05-20T09:50:36.895550+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.9/json/__init__.py", line 346, in loads
2021-05-20T09:50:36.895550+00:00 app[web.1]:     return _default_decoder.decode(s)
2021-05-20T09:50:36.895550+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.9/json/decoder.py", line 337, in decode
2021-05-20T09:50:36.895551+00:00 app[web.1]:     obj, end = self.raw_decode(s, idx=_w(s, 0).end())
2021-05-20T09:50:36.895551+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.9/json/decoder.py", line 355, in raw_decode
2021-05-20T09:50:36.895552+00:00 app[web.1]:     raise JSONDecodeError("Expecting value", s, err.value) from None
2021-05-20T09:50:36.895552+00:00 app[web.1]: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

views.py

from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
# Create your views here.
from django.shortcuts import render, HttpResponse
import requests
import json

from datetime import datetime, timedelta
import ast

from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required

from django.conf import settings
from django.core.mail import send_mail

from django.contrib import messages
from vaccine.models import VaccineSlot


# Email settings

from django.conf import settings
from django.core.mail import send_mail


# Create your views here.
@login_required(login_url='login')
def vaccineHome(request):
    return render(request, 'vaccine/vaccine_home.html')


def handleVaccine(request):
    # Write your STATE here!

    STATE_ID = 0
    # Write your DISTRICT here!
    DISTRICT_ID = 0
    # Setting AGE = 45 here in order to show the live notification demo
    AGE = 45  # Write the minimum age group for which you wanna get notified!
    headers = {
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"
    }
    STATE_ID_ENDPOINT = "https://cdn-api.co-vin.in/api/v2/admin/location/states"
    DISTRICT_ID_ENDPOINT = "https://cdn-api.co-vin.in/api/v2/admin/location/districts"
    ENDPOINT = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByDistrict"
    todays_date = datetime.now()
    DATE = f"{todays_date.day}-{todays_date.month}-{todays_date.year}"

    response = requests.get(f"{STATE_ID_ENDPOINT}", headers=headers)
    states = response.json()["states"]

    if request.method == 'POST':
        STATE = request.POST['state_name']
        DISTRICT = request.POST['district_name']
        email = request.POST['email']
        AGE = request.POST['age']

        if len(STATE) < 2 or len(DISTRICT) < 2 or len(email) < 4 or isinstance(int(AGE), int) == False:
            messages.error(request, "Please fill up the form correctly!")
            return redirect('vaccine')

        else:

            # print(states)
            for state in states:

                if state["state_name"] == STATE:
                    STATE_ID = state["state_id"]
                    print(STATE_ID)
                    break

            if STATE_ID == 0:
                messages.error(request, f"There is no state named {STATE}")
                # print(f"There is no state named {STATE}")
                return redirect('vaccine')

            response = requests.get(
                f"{DISTRICT_ID_ENDPOINT}/{STATE_ID}", headers=headers)
            districts = response.json()["districts"]

            for district in districts:
                if district["district_name"] == DISTRICT:
                    DISTRICT_ID = district["district_id"]
                    print(DISTRICT_ID)
                    break

            if DISTRICT_ID == 0:
                messages.error(
                    request, f"There is no district named {DISTRICT} in state {STATE}")
                # print(f"There is no district named {DISTRICT} in state {STATE}")
                # exit()
                return redirect('vaccine')
            vaccine_enquiry = VaccineSlot(
                state_name=STATE, district_name=DISTRICT, age=int(AGE), email_notification=email)
            vaccine_enquiry.save()
            messages.success(
                request, "Your request has been successfully sent.")
    if check_vaccine(ENDPOINT, DISTRICT_ID, DATE,
                     headers, int(AGE), vaccine_enquiry, request):
        messages.info(
            request, f"HURRY! Vaccine is availabe for age {AGE}.Details of the centers has been sent to your mail id.")
    else:
        messages.warning(
            request, f"\nNO Slot Available in the district {DISTRICT} for age {AGE} in this week as of {DATE}.")

    return redirect('vaccine')

# Function for getting center names


def check_vaccine(ENDPOINT, DISTRICT_ID, DATE, headers, AGE, vaccine_enquiry, request):
    response = requests.get(
        f"{ENDPOINT}?district_id={DISTRICT_ID}&date={DATE}", headers=headers)

    vaccine_slots = response.json()
    print(vaccine_slots)

    slot_available = False
    center_count = 1
    slots_data = ""
    for center in vaccine_slots["centers"]:
        # print(center)
        for session in center["sessions"]:
            if session["min_age_limit"] <= AGE and len(session["slots"]) > 0 and session["available_capacity"] > 0:
                slot_available = True
                slots_data += f"\n{center_count}) {str(center['name'])} on {str(session['date'])}\nOpening Time:{str(center['from'])}\tClosing time: {str(center['to'])}\nCENTER ADDRESS: {str(center['address'])}\nSTATE NAME: {str(center['state_name'])}\nDISTRICT NAME: {str(center['district_name'])}\nPINCODE: {str(center['pincode'])}\nVACCINE: {session['vaccine']}\nAVAILABLE CAPACITY: DOSE 1 = {str(session['available_capacity_dose1'])}\tDOSE 2 = {str(session['available_capacity_dose2'])}\nMinimum Age Limit: {str(session['min_age_limit'])}\nFee Type: {str(center['fee_type'])}\n------------------------------------------------------------------------------------------------------------------------------"
                center_count += 1
                # print(f"Center Name\t{center['name']}")
                # print(f"Slots available\t{session['slots']}")
                # print("-----------------------------------")
                break

    if slot_available:
        notification_data = f"   HURRY! Vaccine is availabe for age {AGE} at these centers: {slots_data}"

        print(notification_data)
        context = {'slots': slots_data}
        subject = 'welcome to TASK world\'s Vaccine Notification '
        message = notification_data
        email_from = settings.EMAIL_HOST_USER
        recipient_list = [vaccine_enquiry.email_notification]
        send_mail(subject, message, email_from, recipient_list)
        return True
    # notify.send(notification_data)
    else:

        notification_data = f"\nNO Slot Available in the district {vaccine_enquiry.district_name} for age {AGE} in this week as of {DATE}."
        print(notification_data)
        subject = 'welcome to TASK world\'s Vaccine Notification '
        message = notification_data
        email_from = settings.EMAIL_HOST_USER
        recipient_list = [vaccine_enquiry.email_notification]
        send_mail(subject, message, email_from, recipient_list)
        return False

    

【问题讨论】:

    标签: python json django api heroku


    【解决方案1】:

    您的代码在该行失败

    states = response.json()["states"]
    

    response 基本上是:

    response = requests.get("https://cdn-api.co-vin.in/api/v2/admin/location/states")
    

    当我在浏览器中访问此 URL 时,我得到:

    403 ERROR
    The request could not be satisfied.
    Request blocked. We can't connect to the server for this app or website at this time. There might be too much traffic or a configuration error. Try again later, or contact the app or website owner.
    If you provide content to customers through CloudFront, you can find steps to troubleshoot and help prevent this error by reviewing the CloudFront documentation.
    Generated by cloudfront (CloudFront)
    Request ID: ------------------------------------
    

    因此response.json() 失败。

    【讨论】:

    • 这就是我所看到的:i.imgur.com/4F6yNJG.png Heroku 可能也看到了类似的东西。
    • 我真的不知道发生了什么。它在我的本地主机上运行良好。
    • CDN 的工作方式对某些人可能会失败,而对其他人却有效。变化也需要一段时间才能出现。无论哪种方式,这都是https://cdn-api.co-vin.in/api/v2/admin/location/states 的网站所有者必须弄清楚的。作为消费者,您无能为力。您可以尝试使用代理和 VPN 或将其托管在不存在问题的不同服务器上,但这不是理想的解决方案,因为故障可能会再次出现。也许你可以找到一个没有隐藏在 CDN 后面的 REST 访问。
    猜你喜欢
    • 2021-04-28
    • 1970-01-01
    • 2011-11-11
    • 1970-01-01
    • 1970-01-01
    • 2014-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多