I am getting a JSON Decode error at /charge when data = json.loads(request.body).
I am working with stripe api as well as fetch api.
The full error is this:
Traceback (most recent call last):
File "/home/antariksh/Desktop/Python Files/Owlet/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/antariksh/Desktop/Python Files/Owlet/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/antariksh/Desktop/Python Files/Owlet/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/antariksh/Desktop/Python Files/Owlet/env/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/antariksh/Desktop/Python Files/Owlet/Menu/views.py", line 151, in charge
data = json.loads(request.body)
File "/usr/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.7/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
That is the error. My code for the /charge/ view is this:
#csrf_exempt
def charge(request):
if request.method == 'POST':
print(request.POST)
transaction_id = uuid.uuid4().hex
data = json.loads(request.body)
print(data)
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, isComplete=False, status='Created')
else:
order, customer = guestOrder(request, data)
total = data['form']['total']
order.transaction_id = transaction_id
order.isComplete = True
order.status = 'Accepted'
order.save()
ShippingAddress.objects.create(
customer = customer,
order = order,
address = data['shipping']['address'],
city = data['shipping']['city'],
state = data['shipping']['state'],
zipcode = data['shipping']['zipcode'],
)
mailOrder(data['form']['email'], order)
return redirect(reverse('menupage'))
The JSON is fine since I checked everything which is parsed and when I ran the code. It saves the data in the database but still shows the error page. The javascript is this:
var url = '/charge/'
fetch(url, {
method:'POST',
headers:{
'Content-Type':'application/json',
'X-CSRFToken': csrftoken
},
body:JSON.stringify({'form':userData, 'shipping':shippingData}),
})
.then((response) => {
response.json()
})
.then((data) => {
console.log(data)
swal({
icon: "success",
text: "Transaction Completed"
});
cart = {}
document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/"
});
The above javascript is fine in terms of syntax. If there is some problem in JSON or anything please help. Help is much appreciated. Please look and tell me what is wrong. Any advice is also much appreciated. I haven't shared the stripe API code.
Related
Can anyone please help me solve this error? When I check out as a logged-in user and press the make payment button it clears the cart and does everything that it is supposed to. The problem is when I do the same for a guest user it does not clear the cart or register anything in the database. The payment button does nothing.
error
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "D:\django\ecommerce\ecomm\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "D:\django\ecommerce\ecomm\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\django\ecommerce\ecommerce\store\views.py", line 73, in processOrder
customer, order = guestOrder(request, data)
File "D:\django\ecommerce\ecommerce\store\utils.py", line 66, in guestOrder
customer, created = Customer.objects.get_or_create(
File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\query.py", line 588, in get_or_create
return self.create(**params), True
File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\query.py", line 453, in create
obj.save(force_insert=True, using=self.db)
File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\base.py", line 726, in save
self.save_base(using=using, force_insert=force_insert,
File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\base.py", line 763, in save_base
updated = self._save_table(
File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\base.py", line 868, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\base.py", line 906, in _do_insert
return manager._insert(
File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\query.py", line 1270, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\models\sql\compiler.py", line 1416, in execute_sql
cursor.execute(sql, params)
File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\backends\utils.py", line 98, in execute
return super().execute(sql, params)
File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\backends\utils.py", line 66, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
return executor(sql, params, many, context)
File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
return self.cursor.execute(sql, params)
File "D:\django\ecommerce\ecomm\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: store_customer.email
Here is guestOrder function in the utils.py file.
Utils.py
def guestOrder(request, data):
print('User is not logged in...')
print('Cookies:', request.COOKIES)
name = data['form']['name']
email = data['form']['email']
cookieData = cookieCart(request)
items = cookieData['items']
customer, created = Customer.objects.get_or_create(
email = email
)
customer.name = name
customer.save()
order = Order.objects.create(
customer = customer,
complete = False,
)
for item in items:
product = Product.objects.get(id=item['product']['id'])
OrderItem = OrderItem.objects.create(
product = product,
order=order,
quantity=item['quantity'],
)
return customer, order
It is the processOrder function in views.py file.
views.py
def processOrder(request):
transaction_id = datetime.datetime.now().timestamp()
data = json.loads(request.body)
if request.user.is_authenticated:
customer = request.user.customer
order, created = Order.objects.get_or_create(customer=customer, complete=False)
else:
customer, order = guestOrder(request, data)
total = float(data['form']['total'])
order.transaction_id = transaction_id
if total == float(order.get_cart_total):
order.complete = True
order.save()
if order.shipping == True:
ShippingAddress.objects.create(
customer=customer,
order=order,
address=data['shipping']['address'],
city=data['shipping']['city'],
state=data['shipping']['state'],
zipcode=data['shipping']['zipcode'],
)
return JsonResponse('Payment Complete!', safe=False)
checkout.html
document.getElementById('make-payment').addEventListener('click', function(e){
submitFormData()
})
function submitFormData(){
console.log('Payment-Button Clicked')
var userFormData = {
'name': null,
'email': null,
'total':total,
}
var shippingInfo = {
'address': null,
'city': null,
'state':null,
'zipcode': null,
}
if(shipping != 'False'){
shippingInfo.address = form.address.value
shippingInfo.city = form.city.value
shippingInfo.state = form.state.value
shippingInfo.zipcode = form.zipcode.value
}
if(user == 'AnonyousUser'){
userFormData.name = form.name.value
userFormData.email = form.email.value
}
var url = '/process_order/'
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrftoken,
},
body: JSON.stringify({'form': userFormData, 'shipping': shippingInfo})
})
.then((response) => response.json())
.then((data) => {
console.log('Success:', data);
alert('Transaction Complete');
cart = {}
document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/"
window.location.href = "{% url 'store' %}"
})
}
error in process_order
JSONDecodeError at /process_order/
Expecting value: line 1 column 1 (char 0)
From the error log, it looks like you are not setting any email id for the guest user and trying to create a Customer object which requires a valid email id.
email = data['form']['email']
This must be setting None for email.
You can try giving a random email id or a default guest email id for the guest user as a work around.
import requests
I am trying to send data to an API which works fine but all of a sudden i start getting JSON error
This is the code
def payment(phone, receiver_phone, amount):
req_header = os.environ.get('APP_KEY')
payload = {
'receiver_phone': receiver_phone,
'amount': amount,
'payer_phone': phone
}
res = requests.post('https://sspay.com/payment?key={0}'.format(req_header), data=payload)
return res.json()
print(payment('07XXXXXX', '0XXXXXXXXX', '1'))
This is the output i get
Traceback (most recent call last):
File "test.py", line 25, in <module>
print(payment('07xxxxx', '09xxxxxxxx', '1'))
File "test.py", line 14, in payment
return res.json()
File "/home/pc/.virtualenvs/talk/lib/python3.8/site-packages/requests/models.py", line 897, in json
return complexjson.loads(self.text, **kwargs)
File "/home/pc/.virtualenvs/talk/lib/python3.8/site-packages/simplejson/__init__.py", line 516, in loads
return _default_decoder.decode(s)
File "/home/pc/.virtualenvs/talk/lib/python3.8/site-packages/simplejson/decoder.py", line 370, in decode
obj, end = self.raw_decode(s)
File "/home/pc/.virtualenvs/talk/lib/python3.8/site-packages/simplejson/decoder.py", line 400, in raw_decode
return self.scan_once(s, idx=_w(s, idx).end())
simplejson.scanner.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
use the code below - it will make you to find the issue
req_header = os.environ.get('APP_KEY')
res = requests.post('https://sspay.com/payment?key={0}'.format(req_header), data=payload)
if res.status_code == 200:
data = res.json()
return data
else:
print('We have a problem. status code : {}'.format(res.status_code))
you are not checking the API response (status code)
what if req_header is None
This is the code in my html in script tags
document.getElementById('payment-info').addEventListener('click',function(e){
submitFormData()
})
function submitFormData(){
console.log('Payment Button Clicked')
var userFormData={
'name':null,
'email':null,
'total':total,
}
var shippingInfo={
'address':null,
'city':null,
'state':null,
'zipcode':null,
}
shippingInfo.address = form.address.value
shippingInfo.city = form.city.value
shippingInfo.state = form.state.value
shippingInfo.zipcode = form.zipcode.value
var url="/process_order/"
fetch(url, {
method:'POST',
headers:{
'Content-Type':'application/json',
'X-CSRFToken':csrftoken,
},
body:JSON.stringify({'form':userFormData,'shipping':shippingInfo}),
})
.then((response) => response.json())
.then((data) => {
console.log('Success:',data);
alert('Transaction Completed')
window.location.href="{% url 'index' %}"
})
}
And this is my views.py
def processOrder(request):
transaction_id=datetime.datetime.now().timestamp()
data = json.loads(request.body)
customer=request.user.customer
order, created=Order.objects.get_or_create(customer=customer,complete=False)
total=float(data['form']['total'])
order.transaction_id=transaction_id
if total == float(order.get_cart_total):
order.complete = True
order.save()
ShippingAddress.objects.create(
customer=customer,
order=order,
address=data['shipping']['address'],
city=data['shipping']['city'],
state=data['shipping']['state'],
zipcode=data['shipping']['zipcode'],
)
It was working fine till i added data=json.loads(request.body) till zipcode. When I added that part of code it starts showing me this error:
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Without adding that section I was able to print this successfully:
print('data:',request.body) but after adding that part of code I am getting this error. I have tried to see what the problem is but its been a day and i am not able to find the problem.
Any help would be appreciated,Thanks
This is the complete error:
Traceback (most recent call last):
File "c:\users\lenovo\appdata\local\programs\python\python38\lib\json\decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
During handling of the above exception (0), another exception occurred:
File "C:\Users\LENOVO\Envs\myapp\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\LENOVO\Envs\myapp\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\LENOVO\Envs\myapp\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\LENOVO\myapp\website\myapp\views.py", line 156, in processOrder
data = json.loads(request.body)
File "c:\users\lenovo\appdata\local\programs\python\python38\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "c:\users\lenovo\appdata\local\programs\python\python38\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "c:\users\lenovo\appdata\local\programs\python\python38\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
Exception Type: JSONDecodeError at /process_order/
Exception Value: Expecting value: line 1 column 1 (char 0)
Is it a correct way to apply celery to class based views?
And, if it is, how can I apply celery to class based Views?
I can’t apply just tagging #app.task above functions inside class.
class ScheduleByFranchiseIdView(generics.RetrieveAPIView):
permission_classes = (IsAdmin,)
serializer_class = ScheduleSerializer
#app2.task
def get(self, request, franchise_id, start = None, end = None):
if start != None and end != None:
query1 = Q(student__profile__franchise__exact=franchise_id)
query2 = Q(start_time__gte=start)
query3 = Q(end_time__lt=end)
queryset = Schedule.objects.filter(query1 & query2 & query3).exclude(status=ScheduleStatus.DELETED).order_by('-id')
serializer = ScheduleSerializer(queryset, many=True)
else:
query1 = Q(student__profile__franchise__exact=franchise_id)
queryset = Schedule.objects.filter(query1).exclude(status=ScheduleStatus.DELETED).order_by('-id')
serializer = ScheduleSerializer(queryset, many=True)
return Response(serializer.data)
I'm trying to test this api and when I call HTTP GET Method to call this api,
i get the error below:
Traceback (most recent call last):
File "C:\Users\Tonyscoding\Desktop\TOCOL\TOCOL_backend\api\testing\test_pagination.py", line 154, in test_admin_schedule_pagination
response = self.client.get('/api/schedule/by/franchise/simple/1/')
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\rest_framework\test.py", line 286, in get
response = super().get(path, data=data, **extra)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\rest_framework\test.py", line 203, in get
return self.generic('GET', path, **r)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\rest_framework\test.py", line 232, in generic
method, path, data, content_type, secure, **extra)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\django\test\client.py", line 422, in generic
return self.request(**r)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\rest_framework\test.py", line 283, in request
return super().request(**kwargs)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\rest_framework\test.py", line 235, in request
request = super().request(**kwargs)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\django\test\client.py", line 503, in request
raise exc_value
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\django\views\generic\base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\rest_framework\views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
raise exc
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\rest_framework\views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\celery\local.py", line 191, in __call__
return self._get_current_object()(*a, **kw)
File "C:\Users\Tonyscoding\Desktop\TOCOL\venv\lib\site-packages\celery\app\task.py", line 392, in __call__
return self.run(*args, **kwargs)
TypeError: get() missing 1 required positional argument: 'request'
my celery worker get the task. I think it's not a worker problem..
In your case might work next scenario. Create a task for hard workload:
#app.task
def schedule_by_franchise(franchise_id, start=None, end=None):
# Do some slow workload, filtering by non-indexed fields or something.
if start is not None and end is not None: # is not None ~20% faster than != None
query1 = Q(student__profile__franchise__exact=franchise_id)
query2 = Q(start_time__gte=start)
query3 = Q(end_time__lt=end)
queryset = Schedule.objects.filter(query1 & query2 & query3).exclude(status=ScheduleStatus.DELETED).order_by('-id')
else:
query1 = Q(student__profile__franchise__exact=franchise_id)
queryset = Schedule.objects.filter(query1).exclude(status=ScheduleStatus.DELETED).order_by('-id')
# Returns something serializable and what could be used for more faster DB search (founded object primary keys might fits)
return tuple(queryset.values_list('id', flat=True))
When executed first GET you should create Celery task and then save it TASK_ID somewhere to later get result:
from celery.result import AsyncResult
class ScheduleByFranchiseIdView(generics.RetrieveAPIView):
permission_classes = (IsAdmin,)
serializer_class = ScheduleSerializer
def get(self, request, franchise_id, start=None, end=None, task_id=None):
if not task_id:
task = schedule_by_franchise.delay(franchise_id, start, end)
return Response({
'task': task.task_id,
'status': 'processing',
'message': f'Please, try again in 10 seconds with following task_id={task.task_id}',
})
else:
result = AsyncResult(task_id)
if result.ready():
ids = result.result
queryset = Schedule.objects.filter(id__in=ids)
serializer = ScheduleSerializer(queryset, many=True)
return Response(serializer.data)
else:
return Response({
'status': 'not_ready_yet',
'message': 'Please, try again in 5 seconds',
})
I am trying to read the file content using URL and return that the content as response in html format but getting the following error:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/opt/lampp/htdocs/rework/Nuclear/RFI/secure/plant/views.py", line 217, in view_reactor
pers = User.objects.get(pk=request.session['id'])
File "/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/backends/base.py", line 57, in __getitem__
return self._session[key]
KeyError: u'id'
I am providing my code below:
site = 'http://127.0.0.1:8000/'
my_list = []
my_list.extend(['home', 'view_reactor'])
if request.GET.get('file') is not None and request.GET.get('file') != '':
file = request.GET.get('file')
if file in my_list:
full_path = site+file
response = urllib.urlopen(full_path)
lines = response.readlines()
return HttpResponse(content=lines, content_type="text/html")
else:
return render(request, 'plant/home.html', {'count': 1})
else:
return render(request, 'plant/home.html', {'count': 1})
def view_reactor(request):
""" This function for to get serch screen. """
pers = User.objects.get(pk=request.session['id'])
root = []
user_name = pers.uname
count = 1
root.append(
{'username': user_name,
'count': count
})
return render(request, 'plant/view_reactor.html',
{'user': root, 'count': 1})
Here I am passing the the value in query string like this http://127.0.0.1:8000/createfile/?file=view_reactor and finally I need the response of http://127.0.0.1:8000/view_reactor page in html format. But in my code I am getting this error.
The error is saying that there is no id key in your session dictionary. In the following line:
pers = User.objects.get(pk=request.session['id'])
And to me it looks redundant to get a user like this. You should be able to get a user simply by doing this:
pers = request.user
Provided that you have auth middleware installed.
Second option (not tested though):
pers = User.objects.get(pk=request.session['_auth_user_id'])