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)
Related
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)
I have a mesh.obj file and I would like to create an endpoint for it. For example, the endpoint could be of the form 'path/to/mesh'. How would I do this?
In your urls.py:
url(r'^test-files/(?P<name>.+)/$', views.test_files, name='test_files'),
In your views.py:
from django.http.response import HttpResponse
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt # (Allows file download with POST requests, can be omitted)
def test_files(request, name):
if name == "myxml":
fsock = open("/djangopath/data/static/files/my.xml", "rb")
return HttpResponse(fsock)
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)
I am trying to copy a folder using the google api, python and Django and have managed to get things working with an adaptation of the code found here
But when I try to copy a folder I get:
< HttpError 400 when requesting https://www.googleapis.com/drive/v3/files/FileId/copy?alt=json returned "Bad Request">
import os
import logging
import httplib2
from pprint import pprint
from googleapiclient.discovery import build
from django.contrib.auth.decorators import login_required
from django.conf import settings
from django.http import HttpResponseBadRequest
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from django.http import JsonResponse
from django.db.utils import IntegrityError
from .models import Entries, CredentialsModel
from oauth2client.contrib import xsrfutil
from oauth2client.client import flow_from_clientsecrets
from oauth2client.contrib.django_util.storage import DjangoORMStorage
from .pipeline_lib import pipeline_lib as pipeline
FLOW = flow_from_clientsecrets(
settings.GOOGLE_OAUTH2_CLIENT_SECRETS_JSON,
scope=['https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/drive.appdata',
'https://www.googleapis.com/auth/drive.metadata'],
redirect_uri='http://somedomain.com:8000/workflow/oauth2callback')
#login_required
def index(request):
storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential')
credential = storage.get()
if credential is None or credential.invalid == True:
FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY,
request.user)
authorize_url = FLOW.step1_get_authorize_url()
return HttpResponseRedirect(authorize_url)
else:
http = httplib2.Http()
http = credential.authorize(http)
service = build("drive", "v3", http=http)
newfile = {'title': 'New Master 123', 'parents': [{'id': 'folderId'}]}
result = service.files().copy(fileId='folderId',body=newfile).execute()
pprint(result)
# results = service.files().list(pageSize=10,fields="nextPageToken, files(id, name)").execute()
# items = results.get('files', [])
# if not items:
# print('No files found.')
# else:
# print('Files:')
# for item in items:
# print('{0} ({1})'.format(item['name'], item['id']))
return HttpResponse("Hello, world. You're at the index.")
#login_required
def auth_return(request):
credential = FLOW.step2_exchange(request.GET)
storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential')
storage.put(credential)
return HttpResponseRedirect("/workflow")
The problem was that I was attempting to copy a folder and apparently files().copy doesn't operate on a folder at least not one with children but I haven't tested the caveat yet.
After replacing the id of the folder I wanted to copy with the file id of a pdf in the same parent the function ran with out error.
Edit - Now that I've figured this out for myself I stumbled upon a stack overflow post that explains why this is.
In Google Drive SDK how do you copy a folder?
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.