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)
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 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)
One of my company's project is in Django and I was assigned to a task to 'add authentication to the top-level router' so we don't forget to add an authentication code to every view, such as:
if not request.user.is_authenticated:
return HttpResponseRedirect('/admin/login/?next=/admin/some-page/')
After doing a bit of research I found out that this can be accomplished by writing my own middleware. I was not familiar at all with the concept until doing my homework. So now I am trying to write a LoginRequiredMiddleware class that intercepts every request and sends the user to the login page if not authenticated and, after authentication, to the original page the user was trying to access.
This is the code I have so far.
middleware.py
from django.conf import settings
from django.http import HttpResponseRedirect
from django.utils.deprecation import MiddlewareMixin
from django.utils.http import is_safe_url
import re
EXEMPT_URLS = [re.compile(settings.LOGIN_REDIRECT_URL.lstrip('/'))] # '/admin'
class LoginRequiredMiddleware(MiddlewareMixin):
def process_request(self, request):
assert hasattr(request, 'user'), "The Login Required Middleware"
if not request.user.is_authenticated:
path = request.path_info.lstrip('/')
if not any(m.match(path) for m in EXEMPT_URLS):
redirect_to = settings.LOGIN_REDIRECT_URL
if len(path) > 0 and is_safe_url(
url=request.path_info, allowed_hosts=request.get_host()):
redirect_to = f"{settings.LOGIN_REDIRECT_URL}/login?next={request.path_info}"
return HttpResponseRedirect(redirect_to)
I have already registered the middleware in the MIDDLEWARE list in settings.py and included both SessionMiddleware and AuthenticationMiddleware but I have not managed to get it to work. I can access a page that requires authentication in incognito mode, for example, without logging in.
I would like some tips on what am I doing wrong or which better path I should be following.
import re
from django.conf import settings
from django.shortcuts import redirect
from django.contrib.auth import logout
from django.utils.deprecation import MiddlewareMixin
EXEMPT_URLS = [re.compile(settings.LOGIN_URL.lstrip('/'))]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
EXEMPT_URLS += [re.compile(url) for url in settings.LOGIN_EXEMPT_URLS]
# Other login exempt urls can be added in settings with 'LOGIN_EXEMPT_URLS'
class LoginRequiredMiddleware(MiddlewareMixin):
def __init__(self, get_response):
self.get_response = get_response
def process_request(self, request):
assert hasattr(request, 'user')
path = request.path_info.lstrip('/')
for endpoint in ["api/", "settings", "mfa", "reset"]:
if path.startswith(endpoint):
return self.get_response(request)
url_is_exempt = any(url.match(path) for url in EXEMPT_URLS)
if path == settings.LOGOUT_URL.lstrip('/'):
logout(request)
if request.user.is_authenticated and url_is_exempt:
# If the user is authenticated and the URL is in the exempt list
# redirect to the login page
return redirect(settings.LOGIN_REDIRECT_URL)
elif request.user.is_authenticated or url_is_exempt:
# Do nothing if the user is authenticated and the URL is not in the
# exempt list
return None
else:
# Trying to access any page as a non authenticated user
return redirect(f"{settings.LOGIN_URL}?next=/{path}")
So I followed the instructions from the answers on this thread:
#csrf_exempt does not work on generic view based class
However, when I send POST requests via Postman, it still keeps throwing 403 error and I wonder what I am missing here. I tried the last answer(using braces.views and CsrfExemptMixin) as well and it still wouldn't work. Below is my code so far
import json
import jwt
from psr.settings import SECRET_KEY
from django.http import HttpResponse, JsonResponse
from django.contrib.auth.forms import AuthenticationForm
from django.contrib import messages
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth import views as auth_views
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from braces.views import CsrfExemptMixin
from .models import User
class LoginView(auth_views.LoginView):
#method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
return super(LoginView, self).dispatch(request, *args, **kwargs)
def post(self, request):
form = AuthenticationForm(data = request.POST)
if form.is_valid():
user = authenticate(email=request.POST['email'], password=request.POST['password'])
if user is not None:
messages.add_message(request, messages.SUCCESS, "Welcome back, {}".format(user))
login(request, user)
token = jwt.encode({'id': user.id}, SECRET_KEY, algorithm='HS256').decode('utf-8')
return JsonResponse({'token': token}, status=200)
Am I missing something here?
Thanks a lot in advance!
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.