How to give user input to Django RestAPI using postman? - python

I have made an DjangoRestApi and giving user input using postman(POST method).but the error is
TypeError: Object of type 'JSONDecodeError' is not JSON serializable
it is showing in django server where i am going wrong please help Thanks
views.py
import spacy
from django.shortcuts import render,HttpResponse
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from django.http import JsonResponse
from django.core import serializers
from django.conf import settings
import json
nlp = spacy.load('en_core_web_sm')
#api_view(["POST"])
def nounphrases(requestdata):
try:
text = json.loads(requestdata.body)
nounphrases = []
for word in (nlp((text))):
c = (word.lemma_)
nounphrases.append(c)
output = [{"nounphrases" : nounphrases }]
return JsonResponse(json.dumps(output))
except ValueError as e:
return Response(e,status.HTTP_400_BAD_REQUEST)

Related

How to verify Shopify webhook in Django?

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)

Upload image to Firebase using Django

I have a Django rest API, in which there is an API to get an image from formdata.
from django.shortcuts import render
from django.http.response import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework import status
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from django.conf import settings
import os
import io
from rest_framework.decorators import api_view
import firebase_admin
from firebase_admin import credentials, firestore, storage
cred = credentials.Certificate("JSON FILE PATH")
firebase_admin.initialize_app(cred,{'storageBucket': 'BUCKET URL'})
#api_view(['GET','POST'])
def login(request):
if request.method == 'POST':
data = request.data
if(type(data)!=dict):
data=data.dict()
file_obj=data['image']
fileName=file_obj.name
blob=bucket.blob(fileName)
blob.upload_from_file(file_obj.file)
blob.make_public()
print("File url", blob.public_url)
return JsonResponse({'username':'Testing post response'})
elif request.method == 'GET':
return JsonResponse({'username':'Testing get response'})
Now, when I send an image in formdata, it is uploading in firebase but not in image format, instead, it is uploading as application/octet-stream type and image is not being displayed. can anyone please help me with this?
change this line
blob.upload_from_file(file_obj.file)
**to**
blob.upload_from_file(file_obj, content_type = file_obj.content_type)

How to give user input dynamically in API?

I am making an API using Django. Since I am giving static type input and getting output in json format. how to give userinput dynamically.
views.py
from django.shortcuts import render,redirect
from django.views.generic import TemplateView
from .models import *
from django.http import HttpResponse
from django.views.generic.edit import FormView
from .forms import TweetForm
from django.views import View
import json
import pdb
import tweepy
from pprint import pprint
import pickle
consumer_key = 'VR95CmIMrv7q7vfDoPcjC8NZS'
consumer_secret = 'YlWo6BzDnhXozSZnvnN1cIcjvRKrJFJVnYA9vvqMDocOdjyBNu'
access_key = '1006840281361047553-JQPFugH9xVNifKRY1b4BjgpdTLiVND'
access_secret = '5R3DXQmf6Xf3FwZHZzqSU3P3oYQAReUqwux9ttj5Gj7K5'
def get_tweets(request):
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
number_of_tweets=10
tweets = api.user_timeline("realdonaldtrump")
tmp= []
for tweet in tweets:
tmp.append({"text":tweet.text,"user":tweet.user.name,"retweet_count":tweet.retweet_count,"img":tweet.user.profile_image_url})
return HttpResponse(json.dumps(tmp))
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'Tweet/$', views.get_tweets, name='Tweet'),
]
that output is right but we can see tweets = api.user_timeline("realdonaldtrump") line in views.py static input.how to give it dynamically
def get_tweets(request, user):
...
tweets = api.user_timeline(user)
...
return HttpResponse(json.dumps(tmp))
With adding user to view function, you need to change the url a bit
urlpatterns = [
url(r'Tweet/(?P<user>[a-zA-Z0-9_\-]+)/$', views.get_tweets, name='Tweet'),
]
Or you can use the get key and values from the link with request.GET.get('user') and pass that in without needing to /Tweet/realdonaldtrump/ but in that case it would be /Tweet/?user=realdonaldtrump so it is your choice to choose whichever you want.

Django REST UnitTest No file was submitted

I successfully implement with small cases. Then I started to work with bigger structure. And I got the error.
Error:
No file was submitted.
import tempfile
from unittest import skip
from django.conf import settings
from django.contrib.auth.models import User
from django.core.files import File
from django.core.files.uploadedfile import SimpleUploadedFile
from model_mommy import mommy
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase, APIClient
class CustomerFromExcelViewsetTest(APITestCase):
def setUp(self):
self.client = APIClient()
self.soken_staff = mommy.make(User, username='spearhead')
self.user = mommy.make(User, username='Justin')
settings.MEDIA_ROOT = tempfile.mkdtemp()
def test_upload_file(self):
"""Expect created_user, and updated_user correct set"""
file = File(open('./soken_web/apps/uploaded_files/complete-customer.xlsx', 'rb'))
uploaded_file = SimpleUploadedFile('new_excel.xlsx', file.read(), content_type='multipart/form-data')
data = {
file: uploaded_file,
}
self.client.force_authenticate(user=self.user)
response = self.client.post(reverse('api:customer_from_excel-list'), data, format='multipart')
response.render()
self.assertEqual(status.HTTP_201_CREATED, response.status_code)
Here they are the models, serializers, and viewsets
models.py https://gist.github.com/elcolie/52daf2bd144af82b348f7353656be434
serializers.py
https://gist.github.com/elcolie/7f097642c4a752e76044c6938c49e097
viewsets.py
https://gist.github.com/elcolie/34fa66632209f14624899d997919d3fb
After a day I could not figure out where is the that bug.
References:
DRF APITestCase not use `multipart` with other param
looks like you missed quotes in data dict. It should be:
data = {
'file': uploaded_file,
}

Problem with import custun storage. Django

Hi I'm siting with my custom storage system 1 day. And now when I'm trying import it it gives me this Error.
I put in file models.py
from FTPStorage import FTPStorage
import datetime
from django.db import models
fs=FTPStorage()
class Upload(models.Model):
"""Uploaded files."""
file = models.FileField(upload_to='uploads', store=fs)
timestamp = models.DateTimeField(default=datetime.datetime.now)
notes = models.CharField(max_length=255, blank=True)
class Meta:
ordering = ['-timestamp',]
def __unicode__(self):
return u"%s" % (self.file)
#property
def size(self):
return filesizeformat(self.file.size)
here is my views.py:
from forms import UploadForm
from models import Upload
import ftplib
import os
import datetime
from django.forms import save_instance
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from FTPStorage import FTPStorage
from django.core.files.storage import Storage
def initial(request):
data = {
'form': UploadForm(),
}
return render_to_response('upload.html', data, RequestContext(request))
def upload(request):
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
upload = Upload()
upload.timestamp = datetime.datetime.now()
save_instance(form, upload)
return HttpResponseRedirect(reverse('initial'))
and file custom storage system FTPStorage.py is in direectory app
I have this problem:
Request Method: GET
Request URL: http://localhost:2121/
Exception Type: ViewDoesNotExist
Exception Value:
Could not import app.views. Error was: cannot import name FTPStorage
Exception Location: C:\BitNami DjangoStack\apps\django\django\core\urlresolvers.py in _get_callback, line 134
Please help me. I confuse.
It seems to me that you need to update the PYTHONPATH for your runtime. Based on your error page I think you're using mod_python so try this setting in apache:
PythonPath "sys.path+['/mydir']"
Where /mydir is the full path to wherever the FTPStorage module resides.

Categories

Resources