django testcase post data - python

I want to write a testcase for sending post data to login page. It does not work. I post my code here and wish you can help me. Thanks.
def setUp(self):
"""set up"""
un = 'abc#gmail.com'
pw = '123'
self.user = User.objects.create_user(un, un)
self.user.is_staff = True
self.user.is_superuser = True
self.user.firstname = "John"
self.user.lastname = "Smith"
self.user.password = '123'
self.user.save()
print '*** password: ', self.user.password
def testPost(self):
"""test POST requests"""
post_data = {
'email': 'abc#gmail.com',
'password': '123',
}
response = self.client.post(reverse('myapp_home', post_data))
print response.status_code
The error output is at below.
ERROR: testPost (submngr.tests.model_tests.model_tests.FormsTestCase)
test POST requests
----------------------------------------------------------------------
Traceback (most recent call last):
File "tests/model_tests/model_tests.py", line 117, in testPost
response = self.client.post('/', post_data)
File "/usr/local/lib/python2.7/dist-packages/django/test/client.py", line 449, in post
response = super(Client, self).post(path, data=data, content_type=content_type, **extra)
File "/usr/local/lib/python2.7/dist-packages/django/test/client.py", line 262, in post
return self.request(**r)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "views.py", line 84, in homepage
print results[0].check_password(form.cleaned_data['password'])
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/models.py", line 304, in check_password
return check_password(raw_password, self.password, setter)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/hashers.py", line 42, in check_password
hasher = get_hasher(algorithm)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/hashers.py", line 115, in get_hasher
"setting?" % algorithm)
ValueError: Unknown password hashing algorithm '123'. Did you specify it in the PASSWORD_HASHERS setting?

You have directly stored the user passowrd as a plain string self.user.password = 123 but django stores user passwords using hashing algorithm that is why you are receiving the error. You can set user password by using set_password method of user which will apply hashing algorithm before saving it:
user.set_password('123')
user.save()

Related

Python - how to pass variables in another variables

I'm trying to pass data of two variables into another variable but I'm getting following error:
Traceback (most recent call last):
File "poll_azure_devops_audit_log.py", line 28, in <module>
x = requests.request('GET', URL, proxies=PROXIES, auth=AZURE_AUTH).json()
File "/opt/splunk/lib/python3.7/site-packages/requests/api.py", line 60, in request
return session.request(method=method, url=url, kwargs)
File "/opt/splunk/lib/python3.7/site-packages/requests/sessions.py", line 519, in request
prep = self.prepare_request(req)
File "/opt/splunk/lib/python3.7/site-packages/requests/sessions.py", line 462, in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
File "/opt/splunk/lib/python3.7/site-packages/requests/models.py", line 317, in prepare
self.prepare_auth(auth, url)
File "/opt/splunk/lib/python3.7/site-packages/requests/models.py", line 548, in prepare_auth
r = auth(self)
TypeError: 'str' object is not callable
How do I have to pass the variables USER & PASSWORD into variable AZURE_AUTH?
import sys
import requests
import json
from urllib.parse import quote
from requests.auth import HTTPBasicAuth
ORGANIZATION = 'xxx'
CONTINUATIONTOKEN = None
API_ENDPOINT = 'https://auditservice.dev.azure.com/'
USER = 'xxx'
PASSWORD = 'xxx'
AZURE_AUTH = HTTPBasicAuth('user123', 'password123')
URL = API_ENDPOINT + ORGANIZATION + '/_apis/audit/auditlog?api-version=6.1-preview&skipAggregation=true'
PROXIES = {
'http' : 'http://xxx:8080',
'https' : 'https://xxx:8080',
}
print(URL)
print(AZURE_AUTH)
print(USER)
print(PASSWORD)
print(PROXIES)
x = requests.request('GET', URL, proxies=PROXIES, auth=AZURE_AUTH).json()
print (x)
I think the problem you think you have is not the problem you actually have. To pass USER and PASSWORD to HTTPBasicAuth is done like this:
AZURE_AUTH = HTTPBasicAuth(USER, PASSWORD)
and you can assign any value you want to your USER and PASSWORD variables like this :
USER = 'user123'
PASSWORD = 'password123'
If you get an error it is comming from somewhere else

Django TypeError: sequence item 0: expected str instance, NoneType found

I tried sending email through smtp and email.mime with Django. I have decided not to use the django email because I want to automate sending of emails to several other emails from any user so the user will be required to put in his email and password to his gmail so smtp can send emails using his account to other emails
Internal Server Error: /api/email/1/send/
Traceback (most recent call last):
File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/rest_framework/views.py", line 505, in dispatch
response = self.handle_exception(exc)
File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/rest_framework/views.py", line 465, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
raise exc
File "/home/taycode/Desktop/emailsenderapi/env/lib/python3.6/site-packages/rest_framework/views.py", line 502, in dispatch
response = handler(request, *args, **kwargs)
File "/home/taycode/Desktop/emailsenderapi/api/views.py", line 71, in post
serializer.send(email_object_id=pk, validated_data=serializer.validated_data)
File "/home/taycode/Desktop/emailsenderapi/api/serializers.py", line 61, in send
sender.send()
File "/home/taycode/Desktop/emailsenderapi/api/utils.py", line 44, in send
self.s.send_message(msg=self.msg)
File "/usr/lib/python3.6/smtplib.py", line 936, in send_message
from_addr = email.utils.getaddresses([from_addr])[0][1]
File "/usr/lib/python3.6/email/utils.py", line 112, in getaddresses
all = COMMASPACE.join(fieldvalues)
TypeError: sequence item 0: expected str instance, NoneType found
This is my sender class which I created
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from os.path import basename
class Sender:
def __init__(self, email, password):
host = "smtp.gmail.com"
port = 587
self.email = email
self.s = smtplib.SMTP(host=host, port=port)
self.s.starttls()
self.s.login(email, password)
self.msg = MIMEMultipart()
def add_attachments(self, path):
with open(path, "rb") as fil:
part = MIMEApplication(
fil.read(),
Name=basename(path)
)
# After the file is closed
part['Content-Disposition'] = 'attachment; filename="%s"' % basename(path)
self.msg.attach(part)
def add_body(self, body):
self.msg.attach(MIMEText(body, "plain"))
return self.msg
def add_recipient(self, email):
self.msg['To'] = email
return self.msg
def add_subject(self, subject):
self.msg['subject'] = subject
return self.msg
def send(self):
print(dict(self.msg))
print(self.s)
self.s.send_message(msg=self.msg)
del self.msg
self.s.quit()
this is my serializer.py
from sender.models import EmailObject
from .utils import Sender
class SendEmailSerializer(Serializer):
email = serializers.EmailField()
password = serializers.CharField()
#staticmethod
def send(validated_data, **kwargs):
email_object = EmailObject.objects.get(pk=kwargs['email_object_id'])
for recipient in email_object.recipient.all():
sender = Sender(validated_data['email'], validated_data['password'])
sender.add_recipient(str(recipient.email))
sender.add_body(email_object.body)
sender.add_subject(email_object.subject)
for attachment in email_object.attachments.all():
print(attachment.file.path)
sender.add_attachments(attachment.file.path)
sender.send()
This is my views.py
class SendEmail(APIView):
serializer_class = SendEmailSerializer
#staticmethod
def post(request, pk):
serializer = SendEmailSerializer(data=request.data)
if serializer.is_valid():
print(serializer.validated_data)
serializer.send(email_object_id=pk, validated_data=serializer.validated_data)
data = {'status': 'success'}
return Response(data, status=status.HTTP_200_OK)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
It returns error everytime I call the SendEmail view in views.py.
how can I fix this??
smtplib.SMTP().send_messages takes 3 parameters, from, to and message. In your code, you are only sending message to the moethod. You need to replace self.s.send_message(msg=self.msg) with:
self.s.send_message(self.email, self.msg['To'], self.msg.as_string())

Getting error while reading the file content using Python and Django

I am trying to read the file content using URL and return that the content as response in html format but getting the following error:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/opt/lampp/htdocs/rework/Nuclear/RFI/secure/plant/views.py", line 217, in view_reactor
pers = User.objects.get(pk=request.session['id'])
File "/usr/local/lib/python2.7/dist-packages/django/contrib/sessions/backends/base.py", line 57, in __getitem__
return self._session[key]
KeyError: u'id'
I am providing my code below:
site = 'http://127.0.0.1:8000/'
my_list = []
my_list.extend(['home', 'view_reactor'])
if request.GET.get('file') is not None and request.GET.get('file') != '':
file = request.GET.get('file')
if file in my_list:
full_path = site+file
response = urllib.urlopen(full_path)
lines = response.readlines()
return HttpResponse(content=lines, content_type="text/html")
else:
return render(request, 'plant/home.html', {'count': 1})
else:
return render(request, 'plant/home.html', {'count': 1})
def view_reactor(request):
""" This function for to get serch screen. """
pers = User.objects.get(pk=request.session['id'])
root = []
user_name = pers.uname
count = 1
root.append(
{'username': user_name,
'count': count
})
return render(request, 'plant/view_reactor.html',
{'user': root, 'count': 1})
Here I am passing the the value in query string like this http://127.0.0.1:8000/createfile/?file=view_reactor and finally I need the response of http://127.0.0.1:8000/view_reactor page in html format. But in my code I am getting this error.
The error is saying that there is no id key in your session dictionary. In the following line:
pers = User.objects.get(pk=request.session['id'])
And to me it looks redundant to get a user like this. You should be able to get a user simply by doing this:
pers = request.user
Provided that you have auth middleware installed.
Second option (not tested though):
pers = User.objects.get(pk=request.session['_auth_user_id'])

django rest framweork test: post request broke authentication in get test

I have two test defined using django-rest-framework test library:
def test_read_site_API(self):
"""
Read a Site trough API
"""
self.client.login(email='test#mail.org', password='testing' )
response = self.client.get('/xos/sites/', format='json')
parsed = json.loads(response.content)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(parsed), 1)
self.assertEqual(parsed[0]['login_base'], 'test_')
def test_create_site_API(self):
"""
Create a Site trough API
"""
data = {
'name': "Another Test Site",
'login_base': "another_test_",
'location': [10, 20],
'abbreviated_name': 'test'
}
self.client.login(email='test#mail.org', password='testing' )
response = self.client.post('/xos/sites/', data, format='json')
print(response.content)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(Site.objects.count(), 2)
self.assertEqual(Site.objects.get(name="Another Test Site").count(), 1)
If I run only the first test it is working.
If I run both tests the result is:
======================================================================
ERROR: test_read_site_API (core.tests.SiteTestAPI)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/opt/xos/core/tests.py", line 75, in test_read_site_API
self.client.login(email='test#mail.org', password='testing' )
File "/usr/local/lib/python2.7/site-packages/django/test/client.py", line 563, in login
login(request, user)
File "/usr/local/lib/python2.7/site- packages/django/contrib/auth/__init__.py", line 102, in login
user_logged_in.send(sender=user.__class__, request=request, user=user)
File "/usr/local/lib/python2.7/site- packages/django/dispatch/dispatcher.py", line 198, in send
response = receiver(signal=self, sender=sender, **named)
File "/opt/xos/core/admin.py", line 1908, in cache_credentials
auth = {'username': request.POST['username'],
KeyError: 'username'
Any idea on what can be happening?
Thanks in advance

CookieConflictError - APISID when trying to programmatically login to Google Finance

I'm trying to write a script to programmatically login to Google Finance, view my portfolio and then display results on my desktop. I'm using the requests module, currently stuck on the 'login' part.
I keep getting this error requests.cookies.CookieConflictError: There are multiple cookies with name, 'APISID'
Here is the entire script, the error throws on line 48. I'm guessing it has something to do with requests keep-alive and the connection isn't recycling properly?
#!/usr/bin/env python
import getpass
import re
import requests
email = raw_input("Enter your Google username: ")
password = getpass.getpass("Enter your password: ")
session = requests.Session()
# Define URLs
login_page_url = 'https://accounts.google.com/ServiceLogin?passive=true&service=finance'
authenticate_url = 'https://accounts.google.com/ServiceLoginAuth?service=finance'
gf_home_page_url = 'http://www.google.com/finance/portfolio'
login_page_contents = session.get(login_page_url).text
# Find GALX value
galx_match_obj = re.search(r'name="GALX"\s*value="([^"]+)"', login_page_contents, re.IGNORECASE)
galx_value = galx_match_obj.group(1) if galx_match_obj.group(1) is not None else ''
# Find DSH value
dsh_match_obj = re.search(r'id="dsh"\s*value="([^"]+)"', login_page_contents, re.IGNORECASE)
dsh_value = dsh_match_obj.group(1) if dsh_match_obj.group(1) is not None else ''
# Set up login credentials
login_params = {
'Email': email,
'Passwd': password,
'continue': 'http://www.google.com/finance/portfolio',
'followup': 'http://www.google.com/finance/portfolio',
'service': 'finance',
'GALX': galx_value,
'pstMsg': 0,
'dnConn': '',
'checkConnection': '',
'timeStmp': '',
'secTok': '',
'bgresponse': 'js_disabled',
'PersistentCookie': 'yes'
}
print galx_value
print dsh_value
# Login
r = session.post(authenticate_url, params=login_params) # <- Error thrown here
print r.text
exit
Traceback:
Traceback (most recent call last):
File "crawl.py", line 48, in <module>
r = session.post(authenticate_url, params=login_params)
File "/Users/nathan/Development/Scripts/google-finance-crawler/requests/sessions.py", line 358, in post
return self.request('POST', url, data=data, **kwargs)
File "/Users/nathan/Development/Scripts/google-finance-crawler/requests/sessions.py", line 312, in request
resp = self.send(prep, **send_kwargs)
File "/Users/nathan/Development/Scripts/google-finance-crawler/requests/sessions.py", line 426, in send
history = [resp for resp in gen] if allow_redirects else []
File "/Users/nathan/Development/Scripts/google-finance-crawler/requests/sessions.py", line 163, in resolve_redirects
resp.cookies.update(cookiejar)
File "/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_abcoll.py", line 494, in update
self[key] = other[key]
File "/Users/nathan/Development/Scripts/google-finance-crawler/requests/cookies.py", line 246, in __getitem__
return self._find_no_duplicates(name)
File "/Users/nathan/Development/Scripts/google-finance-crawler/requests/cookies.py", line 285, in _find_no_duplicates
raise CookieConflictError('There are multiple cookies with name, %r' % (name))
requests.cookies.CookieConflictError: There are multiple cookies with name, 'APISID'
It's a bug in requests, see issue 1189.
The current proposed fix is to simply delete line 163 of requests/sessions.py:
resp.cookies.update(cookiejar)

Categories