connection error while using requests module in my django project - python

I was trying to create a django project. Everything was fine until I did a get request using requests.get() in python in my views.py
Following is what my views.py have
from django.http import HttpResponse
from django.shortcuts import render
import re, requests
def codify_data(data_raw):
data = data_raw.json()['data']
if language == 'web':
html_cd = data['sourceCode']
css_cd = data['cssCode']
js_cd = data['jsCode']
def home_page(request):
return render(request,'home/index.html')
def code(request):
link = request.GET.get('link', 'https://code.sololearn.com/c5I5H9T7viyb/?ref=app')
result = re.search(r'https://code.sololearn.com/(.*)/?ref=app',link).group(1)[0:-2]
data_raw = requests.get('https://api2.sololearn.com/v2/codeplayground/usercodes/'+result)
codify_data(data_raw)
The error is shown below:

Related

Shopify webhook request verification for `orders/create` topic returning False in python/django project [duplicate]

How can I verify the incoming webhook from Shopify? Shopify provides a python implementation (of Flask), but how can I do it in Django/DRF?
Set these two variables in the settings.py file
# settings.py
SHOPIFY_HMAC_HEADER = "HTTP_X_SHOPIFY_HMAC_SHA256"
SHOPIFY_API_SECRET = "5f6b6_my_secret"
Then, create a verify webhook function that accepts the Django request as it's parameter
# utils.py
import base64
import hashlib
import hmac
from django.conf import settings
from django.core.handlers.wsgi import WSGIRequest
def verify_shopify_webhook(request: WSGIRequest):
shopify_hmac_header = request.META.get(settings.SHOPIFY_HMAC_HEADER)
encoded_secret = settings.SHOPIFY_API_SECRET.encode("utf-8")
digest = hmac.new(
encoded_secret,
request.body,
digestmod=hashlib.sha256,
).digest()
computed_hmac = base64.b64encode(digest)
return hmac.compare_digest(computed_hmac, shopify_hmac_header.encode("utf-8"))
Then, create a view that accepts the incoming webhook and use the verify_shopify_webhook(...) function to verify the request.
# views.py
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from .utils import verify_shopify_webhook
#method_decorator(csrf_exempt, name="dispatch")
class ShopifyWebhookView(View):
def post(self, request, *args, **kwargs):
verified = verify_shopify_webhook(request=request)
return HttpResponse(status=200 if verified else 403)
If you're using Django REST Framework, you can also use APIView as
# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from .utils import verify_shopify_webhook
class ShopifyWebhookView(APIView):
def post(self, request, *args, **kwargs):
verified = verify_shopify_webhook(request=request)
return Response(status=200 if verified else 403)

Can't call objects from class in loop Python Django

I an newbee to Django and I realise that it is a very silly question but, when I put objects in a HTML code to call index from data base I recieve just text of what I am calling: List of news(item.title)(item.title)(item.title)(item.title)
views.py:
from django.shortcuts import render
from django.http import HttpResponse
from .models import News
def index(request):
news = News.objects.all()
res = '<hi>List of news</h1>'
for item in news:
res += f'<div><p>(item.title)</p></div>'
return HttpResponse(res)
from django.shortcuts import render
from django.http import HttpResponse
from .models import News
def index(request):
news = News.objects.all()
res = '<hi>List of news</h1>'
for item in news:
res += f'<div><p>{item.title}</p></div>'
return HttpResponse(res)

get Json data from request with Django

I'm trying to develop a very simple script in Django, I'd collect a Json data from the request and then store all data in the database.
I developed one python script that I'm using to send the Json data to the Django view, but I'm doing something wrong and I can't understand what, because every time that I run it,I've got "Malformed data!".
Can someone helps me? what am I doing wrong?
Sender.py
import json
import urllib2
data = {
'ids': ["milan", "rome","florence"]
}
req = urllib2.Request('http://127.0.0.1:8000/value/')
req.add_header('Content-Type', 'application/json')
response = urllib2.urlopen(req, json.dumps(data))
Django view.py
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
import json
from models import *
from django.http import StreamingHttpResponse
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def value(request):
try:
data = json.loads(request.body)
label = data['label']
url = data ['url']
print label, url
except:
return HttpResponse("Malformed data!")
return HttpResponse("Got json data")
Your dictionary "data" in sender.py contains only one value with key "ids" but in view.py you are trying to access keys "label" and "url" in this parsed dictionary.

django data not changing dynamically

I wrote a django application to display some data fetched from mongodb in html template. All the order item ids are fetched with status 'APPROVED'
models.py:
from pymongo import MongoClient
class GetNewOrders(object):
def __init__(self):
self.client = MongoClient('localhost',27017)
self.db = self.client['Flipkart']
self.sale_order = list(self.db['sale_order'].find({'status':'APPROVED'}))
def getOrderItemId(self):
oiids = []
for each in self.sale_order:
oiids.append(each['orderItemId'])
return oiids
views.py:
from django.shortcuts import render
from django.http import HttpResponse
from orders.models import GetNewOrders
no = GetNewOrders()
oiids_new = no.getOrderItemId()
def orders(request):
context_dict = {'oiids_new':oiids_new}
return render(request, 'orders/orders.html', context_dict)
i used a for loop in my html file to display that data. If i change the status of a document to 'APPROVED', it does not reflect in my html until i restart the server. How to show the changed data in html without restarting django server?
because GetNewOrders is at module level it is only executed once - you need to move it into the function body:
def orders(request):
no = GetNewOrders()
oiids_new = no.getOrderItemId()
context_dict = {'oiids_new':oiids_new}
return render(request, 'orders/orders.html', context_dict)

Serving XML and HTML with Django

I have a Django App, that has to serve HTML-Files to normal Browsers, that understand HTML, and XML-Files to other clients.
In my views.py I'm trying to differentiate between the different HTTP_ACCEPT tags, the incoming HTTP request has. This seems to work already, since a normal HTML file is served as intended.
Only when i try to serve an XML file, i get an Error saying:
ValueError at /appstore/
The view appstore.views.index didn't return an HttpResponse object.
Here is my views.py
from appstore.models import App
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse
from django.core import serializers
def index(request):
if (request.META['HTTP_ACCEPT'].find('text/html') != -1):
latest_app_list = App.objects.all().order_by('name')[:5]
return render_to_response('appstore/index.html', {'latest_app_list': latest_app_list})
else:
def xml_view(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return HttpResponse(serializers.serialize("xml", result),
mimetype="text/xml")
return wrapper
#xml_view
def index(request):
return App.objects.all()
#xml_view
def get(request, id):
return get_object_or_404(App, pk=app_id)
I hope someone of you can help me.
Thanks in advance.

Categories