Problem with import custun storage. Django - python

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.

Related

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)

Django: create endpoint for a file

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)

django-background-task not functioning

my django-background-task does nothing, even if I just ask it to do something simple like printing a string.
I dont know what I am doing wrong though.
views.py:
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth import update_session_auth_hash
from .forms import UserRegistrationForm
from .models import Player, PlayerStats, TotalLevels
from django.core import management
from background_task import background
import random
# background task
#background(schedule=5)
def play_run():
print('it works!')
# management.call_command('runscript', 'runnerscript')
def random_logo():
logo = random.randint(1, 5)
logo_file = 'logo-nav'+str(logo)+'.png'
return logo_file
# Main website views
def home(request):
return render(request, template_name='main/home.html')
# bloxors website specific views
def homepage(request):
logo_file = random_logo()
return render(request, template_name='bloxors/homepage.html', context={'logo':logo_file})
# view in which background task is called
#login_required
def play_redirect(request):
play_run()
return HttpResponse('Please wait while we redirect you...')
Can someone help me by telling what is going wrong?
As always, I appreciate any and all answers!
While the server is running, open another terminal or command prompt with your virtual environment activated then run python manage.py process_tasks
https://django-background-tasks.readthedocs.io/en/latest/

How to give user input to Django RestAPI using postman?

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)

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,
}

Categories

Resources