Django issue with import models - python

I am very new with django framework.
# Create your views here.
import urllib2
import json
import urllib
from .models import Apiclass
from django.shortcuts import render_to_response
from django.conf import settings as config
def home(request):
obj = Apiclass()
def postme(request):
url = config.API_PROTOCOL+config.API_DOMAIN+config.API_SECURE_USER_URL
# user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {'username' : 'waheeda#auction.com',
'password' : '12345678'
}
# headers = { 'Content-Type' : "application/json" }
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = json.loads(response.read())
return render_to_response("home.html",{'postme':the_page})
And ApiClass is under models/Apiclass.py
I tried many ways to import the model ApiClass
such as
- from app1.models import Apiclass
- from .models import Apiclass
but it still does not work it gave me the errors like this
TypeError at /api
'module' object is not callable
Apiclass.py
I just comment all the implementation when ever I can create object that everything should be good. Here is the Apiclass code
import urllib2
import urllib
import json
from django.conf import settings as config
# Create your models here.
class Apiclass:
api_domain = config.API_DOMAIN

Your should have class Apiclass inside models.py. Also I recommend you to import from full module path .i.e from YOUR_APP.models import Apiclass
If you want folder structure:
models/
__init__.py
and inside __init__.py you could have Apiclass and import as from YOUR_APP.models import Apiclass as well.
Also make sure it is subclassed from django.db.models.Model if it touches database in any way as recommended below.

You haven't subclassed your ApiClass model correctly. It should subclass django Model
from django.db import models
class ApiClass(models.Model):
pass
It's barfing because you are trying to call your class with this:
Apiclass()
but ApiClass doesn't currently have a call method.

Related

Seting Auth headers in Django tests

I am trying to write a test which goes through the signup/login workflow, and then attempts to change the status of a user, which requires them to be logged in. I verified that the first 2 POST requests work (the user is indeed created and then gets a valid auth token after logging in), however I cannot seem to pass in said token in the headers for the 3rd and final POST request. I also checked that the auth_headers variable is indeed set with the correct token, but I keep getting back a 401 status code.
Thanks in advance!
tests.py
from email.headerregistry import ContentTypeHeader
from urllib import request
from wsgiref import headers
from django.http import HttpRequest
from django.test import TestCase, Client
from rest_framework import status
from rest_framework.test import APITestCase
from django.urls import reverse
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User
from profiles_api.serializers import UserProfileSerializer
from django.contrib.auth import get_user_model
from profiles_api.views import UserLoginApiView
client = Client()
User = get_user_model()
class MyTestCase(APITestCase,UserLoginApiView):
def test_add_status_to_profile(self):
response = self.client.post("/api/profile/", data={
'email':"John#gmail.com",
'name':'Pavle',
'password':'password'
})
response = self.client.post("/api/login/", data={
'username':"John#gmail.com",
'password':'password'
})
auth_headers = {
'Authorization': 'Bearer ' + response.json()['token']
}
response = self.client.post("/api/feed/", content_type='application/json', data={
'status_text':'Hello world!'
}, **auth_headers)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)

How to use django cache with REST Framework?

I'm fairly new to Django and try to get a working backend. So far, my backend is working fine, but I don't know, how to respond with custom data:
What I have:
Angular Frontend
Django (REST) backend
A working cache
What I want to achieve:
I want to call an endpoint (lets say backend/weather). When I call this endpoint, I want to check my cache for a weather value. If there is one, I want to send it to the client. If there is none, I want to make an API call, store the retrieved value in my cache and send the value to the client. How can I do this. This is what I have so far:
views.py
from rest_framework import viewsets
from .models import Weather
from .serializers import WeatherSerializer
from django.core.cache import cache
from urllib.request import urlopen
import json
class WeatherView(APIView):
def get(self):
if(cache.get('temp') == None):
url = 'https://api.openweathermap.org/data/2.5/forecast?q=' + '...';
serialized_data = urlopen(url).read()
data = json.loads(serialized_data)
print(data)
cache.set('weatherdata', data, 3600)
else:
data = cache.get('weatherdata')
serializer_class = WeatherSerializer(data)
responseJSON = JSONRenderer().render(serializer_class.data)
return Response(responseJSON)
serializers.py
from rest_framework import serializers
from .models import Weather
class WeatherSerializer(serializers.Serializer):
temp = serializers.DecimalField(max_digits=4, decimal_places=2)
iconName = serializers.CharField()
urls.py
from django.urls import path, include
from . import views
from rest_framework import routers
from django.conf import settings
from django.conf.urls.static import static
router = routers.DefaultRouter()
urlpatterns = [
path('', include(router.urls)),
path('weather', views.WeatherView)
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I get the data from the API. My cache setting and getting are also working. But I don't know how to respond with custom data. I'm getting the following error when calling backend/weather:
TypeError at /weather
__init__() takes 1 positional argument but 2 were given
Request Method: GET
Request URL: http://127.0.0.1:8000/weather
Django Version: 2.2.7
Exception Type: TypeError
Exception Value:
__init__() takes 1 positional argument but 2 were given
Thank you in advance!

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

how to serialize django.conf.settings to json

I am getting this error...
Object of type 'Settings' is not JSON serializable
Here is my code
from django.conf import settings
import json
def get_settings(request):
responce = settings.__dict__
return HttpResponse(json.dumps(responce),content_type='application/json')
django.conf.settings is not Json serializable, thought you can go throught and create dict() then give it to HttpResponse. Hope it helps!
import json
from django.http import HttpResponse
from django.conf import settings
def get_settings(request):
context = {}
for setting in dir(settings):
if setting.isupper():
context[setting] = getattr(settings, setting)
return HttpResponse(json.dumps(context, indent=4), content_type="application/json")

Importing module with class method (webapp2.RequestHandler) to check cookie (GAE-Python)

I need to check a cookie and use the value to set which template to load.
Below is the working code snippet:
import webapp2 as webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
import os
class genericPage(webapp.RequestHandler):
def get(self):
templatepath = os.path.dirname(__file__) + '/../templates/'
ChkCookie = self.request.cookies.get("cookie")
if ChkCookie == 'default':
html = template.render(templatepath + 'default_header.html', {})
else:
html = template.render(templatepath + 'alt_header.html', {})
self.response.out.write(html)
My question is how to move the ChkCookie and if...else statements into a separate module and call it in the code above. Such as with:
# HOW I WANT TO MODIFY THE ABOVE CODE TO SET THE TEMPLATES WITH A COOKIE
import webapp2 as webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
import os
from testmodule import testlibrary
class genericPage(webapp.RequestHandler):
def get(self):
html = testlibrary.ChkCookieClass.ChkCookie()
self.response.out.write(html)
I can successfully import the library/module when I keep the ChkCookie code in the genericPage class and the module only contains a function, like this:
# THIS IS THE MODULE I AM IMPORTING
import webapp2 as webapp
from google.appengine.ext.webapp import template
import os
def SkinChk(ChkCookie):
templatepath = os.path.dirname(__file__) + '/../templates/'
if ChkCookie == 'default':
out = template.render(templatepath + 'default_header.html', {})
else:
out = template.render(templatepath + 'alt_header.html', {})
return out
How would I modify the above module code to have the ChkCookie = self.request.cookies.get("cookie") in there?
You can use: http://webapp-improved.appspot.com/api/webapp2.html#webapp2.get_request to get the request instance in your module.
This is the same as passing self.request to your module.

Categories

Resources