Log warning from Selenium on Django [duplicate] - django

Whenever I try to construct a string based on self.live_server_url, I get python TypeError messages. For example, I've tried the following string constructions (form 1 & 2 below), but I experience the same TypeError. My desired string is the Live Server URL with "/lists" appended. NOTE: the actual test does succeed to create a server and I can manually access the server, and more specifically, I can manually access the exact URL that I'm trying to build programmatically (e.g. 'http://localhost:8081/lists').
TypeErrors occur with these string constructions.
# FORM 1
lists_live_server_url = '%s%s' % (self.live_server_url, '/lists')
# FORM 2
lists_live_server_url = '{0}{1}'.format(self.live_server_url, '/lists')
self.browser.get(lists_live_server_url)
There is no python error with this form (nothing appended to string), albeit my test fails (as I would expect since it isn't accessing /lists).
self.browser.get(self.live_server_url)
Here is the python error that I'm getting.
/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/bin/python3.4 /Applications/PyCharm.app/Contents/helpers/pycharm/django_test_manage.py test functional_tests.lists_tests.LiveNewVisitorTest.test_can_start_a_list_and_retrieve_it_later /Users/myusername/PycharmProjects/mysite_proj
Testing started at 11:55 AM ...
Creating test database for alias 'default'...
Traceback (most recent call last):
File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/wsgiref/handlers.py", line 137, in run
self.result = application(self.environ, self.start_response)
File "/usr/local/lib/python3.4/site-packages/django/test/testcases.py", line 1104, in __call__
return super(FSFilesHandler, self).__call__(environ, start_response)
File "/usr/local/lib/python3.4/site-packages/django/core/handlers/wsgi.py", line 189, in __call__
response = self.get_response(request)
File "/usr/local/lib/python3.4/site-packages/django/test/testcases.py", line 1087, in get_response
return self.serve(request)
File "/usr/local/lib/python3.4/site-packages/django/test/testcases.py", line 1099, in serve
return serve(request, final_rel_path, document_root=self.get_base_dir())
File "/usr/local/lib/python3.4/site-packages/django/views/static.py", line 54, in serve
fullpath = os.path.join(document_root, newpath)
File "/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/posixpath.py", line 82, in join
path += b
TypeError: unsupported operand type(s) for +=: 'NoneType' and 'str'
Am I unknowingly attempting to modify the live_server_url, which is leading to these TypeErrors? How could I programmatically build a string of live_server_url + "/lists"?
Here is the test that I am attempting...
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from django.test import LiveServerTestCase
class LiveNewVisitorTest(LiveServerTestCase):
def setUp(self):
self.browser = webdriver.Chrome()
self.browser.implicitly_wait(3)
def tearDown(self):
self.browser.close()
def test_can_start_a_list_and_retrieve_it_later(self):
#self.browser.get('http://localhost:8000/lists')
#self.browser.get('http://www.google.com')
#lists_live_server_url = '%s%s' % (self.live_server_url, '/lists')
#lists_live_server_url = '{0}{1}'.format(self.live_server_url, '/lists')
lists_live_server_url = self.live_server_url
self.browser.get(lists_live_server_url)
self.assertIn('To-Do', self.browser.title)
header_text = self.browser.find_element_by_tag_name('h1').text
self.assertIn('To-Do', header_text)

See this discussion on Reddit featuring the same error Traceback.
Basically, this is not a problem with anything within the Selenium tests but rather with your project's static file configuration.
From your question, I believe the key line within the Traceback is:
File "/usr/local/lib/python3.4/site-packages/django/views/static.py", line 54, in serve
fullpath = os.path.join(document_root, newpath)
This line indicates that an unsuccessful os.path.join is being attempted within django.views.static.
Set STATIC_ROOT in your project's settings.pyfile and you should be good.

Use StaticLiveServerTestCase instead may help

Related

Api with flask-jwt-extended with authentication problems?

I have built an api with flask-restful and flask-jwt-extended and have correctly configured the validation passages for token expiration and invalidation. However, even though it has built the token expiration and invalid validation callbacks, api does not process correctly and reports the error: Signature has expired
On the server in the cloud, we have a Centos 7 x64 of 16gb ram, running the application using gunicorn in version 19.9.0. Using the miniconda to create the applications' python environments.
In tests in the production environment, the application complains of the expired token. However in a test environment, using Ubuntu 18.04.2, x64 with 16 gb ram, using the same settings with miniconda and gunicorn, the application has no problems executing it, returning the correct message when the token expires.
My jwt.py
from flask import Blueprint, Response, json, request
from flask_jwt_extended import (JWTManager, create_access_token,
create_refresh_token, get_jwt_identity,
jwt_required)
from app.models.core import User
from .schemas import UserSchema
from .utils import send_reponse, user_roles
def configure_jwt(app):
JWT = JWTManager(app)
#JWT.expired_token_loader
def my_expired_token_callback(expired_token):
return Response(
response=json.dumps({
"message": "Expired token"
}),
status=401,
mimetype='application/json'
)
#JWT.invalid_token_loader
def my_invalid_token_callback(invalid_token):
return Response(
response=json.dumps({
"message": "Invalid token"
}),
status=422,
mimetype='application/json'
)
Error log:
[2019-05-23 15:42:02 -0300] [3745] [ERROR] Exception on /api/company [POST]
Traceback (most recent call last):
File "/home/company/miniconda3/envs/api_ms/lib/python3.6/site-packages/flask/app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "/home/company/miniconda3/envs/api_ms/lib/python3.6/site-packages/flask/app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/company/miniconda3/envs/api_ms/lib/python3.6/site-packages/flask_restful/__init__.py", line 458, in wrapper
resp = resource(*args, **kwargs)
File "/home/company/miniconda3/envs/api_ms/lib/python3.6/site-packages/flask/views.py", line 88, in view
return self.dispatch_request(*args, **kwargs)
File "/home/company/miniconda3/envs/api_ms/lib/python3.6/site-packages/flask_restful/__init__.py", line 573, in dispatch_request
resp = meth(*args, **kwargs)
File "/home/company/miniconda3/envs/api_ms/lib/python3.6/site-packages/flask_jwt_extended/view_decorators.py", line 102, in wrapper
verify_jwt_in_request()
File "/home/company/miniconda3/envs/api_ms/lib/python3.6/site-packages/flask_jwt_extended/view_decorators.py", line 31, in verify_jwt_in_request
jwt_data = _decode_jwt_from_request(request_type='access')
File "/home/company/miniconda3/envs/api_ms/lib/python3.6/site-packages/flask_jwt_extended/view_decorators.py", line 266, in _decode_jwt_from_request
decoded_token = decode_token(encoded_token, csrf_token)
File "/home/company/miniconda3/envs/api_ms/lib/python3.6/site-packages/flask_jwt_extended/utils.py", line 107, in decode_token
allow_expired=allow_expired
File "/home/company/miniconda3/envs/api_ms/lib/python3.6/site-packages/flask_jwt_extended/tokens.py", line 138, in decode_jwt
leeway=leeway, options=options)
File "/home/company/miniconda3/envs/api_ms/lib/python3.6/site-packages/jwt/api_jwt.py", line 104, in decode
self._validate_claims(payload, merged_options, **kwargs)
File "/home/company/miniconda3/envs/api_ms/lib/python3.6/site-packages/jwt/api_jwt.py", line 134, in _validate_claims
self._validate_exp(payload, now, leeway)
File "/home/company/miniconda3/envs/api_ms/lib/python3.6/site-packages/jwt/api_jwt.py", line 175, in _validate_exp
raise ExpiredSignatureError('Signature has expired')
jwt.exceptions.ExpiredSignatureError: Signature has expired
I'm trying to understand why the application is able to correctly return the token expiration message in the test environment, where in the production environment it returns the error code 500 Internal Server Error. In addition to fixing this problem in our application.
Based on this link found inside the project repository, I discovered that the problem is related to the flask configuration option called PROPAGATE_EXCEPTIONS, which must be True.
The issue in the flask-jwt-extended repository that helped me find the answer.
This comment states that Flask Restful needs to ignore JWT and JWT Extended Exceptions and provides a simple snippet that solves the issue.
Copying the code from above link,
from flask_jwt_extended.exceptions import JWTExtendedException
from jwt.exceptions import PyJWTError
class FixedApi(Api):
def error_router(self, original_handler, e):
if not isinstance(e, PyJWTError) and not isinstance(e, JWTExtendedException) and self._has_fr_route():
try:
return self.handle_error(e)
except Exception:
pass # Fall through to original handler
return original_handler(e)

Flask Security - Send confirmation email?

I am trying to create a flask boilerplate app and I am running into an error when I try to run a flask-script. I am getting an error that I don't fully understand, the code is broken up into several modules so it may be best to post the link to the repository. The two parts in the traceback that are my code are an import from the app and the creation of the security object.
The two files that are causing conflict are:
manage.py
app/__init__.py
What caused the problem is that I set several security variables to true:
SECURITY_REGISTERABLE = True
SECURITY_SEND_REGISTER_EMAIL = True
SECURITY_CONFIRMABLE = True
SECURITY_CONFIRM_URL = True
SECURITY_EMAIL_SENDER = 'some_email_account'
SECURITY_CONFIRM_LOGIN_WITHOUT_CONFIRMATION = False
SECURITY_TRACKABLE = True
SECURITY_CHANGEABLE = True
The project can be found here:
github link
Traceback (most recent call last):
File "manage.py", line 4, in <module>
from app import app, db, Role, user_datastore
File "C:\Users\...\dev\flask-boilerplate\app\__init__.py", line 22, in <module>
security = Security(app, user_datastore)
File "C:\Users\...\dev\flask-boilerplate\venv\lib\site-packages\flask_security\core.py", line 469, in __init__
self._state = self.init_app(app, datastore, **kwargs)
File "C:\Users\...\dev\flask-boilerplate\venv\lib\site-packages\flask_security\core.py", line 507, in init_app
app.register_blueprint(create_blueprint(state, __name__))
File "C:\Users\...\dev\flask-boilerplate\venv\lib\site-packages\flask_security\views.py", line 383, in create_blueprint
'<token>'),
File "C:\Users\...\dev\flask-boilerplate\venv\lib\site-packages\flask_security\utils.py", line 249, in slash_url_suffix
return url.endswith('/') and ('%s/' % suffix) or ('/%s' % suffix)
AttributeError: 'bool' object has no attribute 'endswith'
SECURITY_CONFIRM_URL must be a string (i.e. SECURITY_CONFIRM_URL='https://google.com)

How to enable HTTPS on Python 2.7 web.py?

I am using Python 2.7.5 with web.py (v0.38) installed on a Linux machine. Below is my code in the most basic form (webhooks.py)
#!/usr/bin/python
import web
urls = ('/.*','WebHooks')
app = web.application(urls, globals())
class WebHooks:
def POST(self):
raw_payload = web.data()
json_encode = json.loads(raw_payload)
if __name__ == '__main__':
app.run()
I execute python webhooks.py 9999
It opens up a local port http://0.0.0.0:9999/
My issue: I have read the documentation located here and I am stumped. Would somebody be able to help me open an HTTPS URL? https://0.0.0.0:9999/
What I have tried
Add the following into my code for testing:
response = app.request("/.*", https=True)
I would get an error: AttributeError: 'module' object has no attribute 'request'
I solved that issue with pip install urllib.py and then adding import urllib to the top of my code but I ended up with a bunch of errors:
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/web/application.py", line 239, in process
return self.handle()
File "/usr/lib/python2.7/site-packages/web/application.py", line 230, in handle
return self._delegate(fn, self.fvars, args)
File "/usr/lib/python2.7/site-packages/web/application.py", line 461, in _delegate
cls = fvars[f]
KeyError: u'WebHooks'
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/web/application.py", line 239, in process
return self.handle()
File "/usr/lib/python2.7/site-packages/web/application.py", line 229, in handle
fn, args = self._match(self.mapping, web.ctx.path)
AttributeError: 'ThreadedDict' object has no attribute 'path'
You're headed down the wrong path, but not to worry. The response = app.request("/.*", https=True) bit you're trying has to do with your application making an https request, rather then handling an https request.
See http://webpy.org/cookbook/ssl
Internally, web.py uses a CherryPyWSGIServer. To handle https, you need to provide the server with an ssl_certificate and ssl_key. Very simply, add a few lines before you invoke app.run():
if __name__ == '__main__':
from web.wsgiserver import CherryPyWSGIServer
ssl_cert = '/path-to-cert.crt'
ssl_key = '/path-to-cert.key'
CherryPyWSGIServer.ssl_certificate = ssl_cert
CherryPyWSGIServer.ssl_private_key = ssl_key
app.run()
Of course, in a full solution, you'll probably want apache or nginx to handle the https portion, but the above is perfect for small applications and testing.

Werkzeug test client and utf-8

Here's the code. When I send both fields it fails.
import unittest
class UnicodeTestCase(unittest.TestCase):
def test_unicode(self):
from cStringIO import StringIO
from flask import Flask, request
app = Flask(__name__)
app.config['TESTING'] = True
#app.route('/', methods=["POST"])
def test_view():
print request.values, request.files
return "OK"
file = (StringIO("0" * 1000), "filename.txt")
string = u"∆_∆"
client = app.test_client(use_cookies=False)
self.assertEquals(200, client.post('/', data={'file': file}).status_code)
self.assertEquals(200, client.post('/', data={'string': string}).status_code)
self.assertEquals(200, client.post('/', data={'file': file, 'string': string}).status_code)
On the last assert it fails with:
Error
Traceback (most recent call last):
File "/Users/user1/tests/test_uni.py", line 108, in test_unicode
self.assertEquals(200, client.post('/', data={'file': file, 'string': string}).status_code)
File "/Users/user1/.virtualenvs/test/lib/python2.7/site-packages/werkzeug/test.py", line 771, in post
return self.open(*args, **kw)
File "/Users/user1/.virtualenvs/test/lib/python2.7/site-packages/flask/testing.py", line 108, in open
follow_redirects=follow_redirects)
File "/Users/user1/.virtualenvs/test/lib/python2.7/site-packages/werkzeug/test.py", line 725, in open
environ = args[0].get_environ()
File "/Users/user1/.virtualenvs/test/lib/python2.7/site-packages/werkzeug/test.py", line 535, in get_environ
stream_encode_multipart(values, charset=self.charset)
File "/Users/user1/.virtualenvs/test/lib/python2.7/site-packages/werkzeug/test.py", line 104, in stream_encode_multipart
write('\r\n\r\n' + value)
File "/Users/user1/.virtualenvs/test/lib/python2.7/site-packages/werkzeug/test.py", line 71, in write
write_binary(string.encode(charset))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 4: ordinal not in range(128)
It works fine when I'm sending both fields with the Postman (a Google Chrome extension).
Is it OK and should I wrap fields with unicode with base64 or something else? Or is it a bug in the werkzeug test client?
Look like test client bug, I already have another bug with test client when direct request work fine, but test client has unexpected result.
For me in https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/test.py#L71 I have string type as str. For string only this method not called, for file only this method do not called with your string. You can try temporary update this method with next for python 2 only:
def write(string):
if isinstance(string, str):
write_binary(string)
else:
write_binary(string.encode(charset))
I created bug for your example: https://github.com/mitsuhiko/flask/issues/973.

Haystack: KeyError in the elasticsearch_backend module

I'm using Django + Haystack + Elasticsearch.
When I send a request to this view
from haystack.views import FacetedSearchView
from .models import Object
class ObjectView(FacetedSearchView):
def extra_context(self):
extra = super(ObjectView, self).extra_context()
if not self.results:
extra['objects'] = Object.objects.all()
else:
searchqueryset = self.form.search()
results = [ result.pk for result in searchqueryset ]
extra['facets'] = self.results.facet_counts()
extra['objects'] = Object.objects.filter(pk__in=results)
extra['results'] = self.results
return extra
this error is raised:
File "/home/deploy/.virtualenvs/deploy/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 115, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/home/deploy/.virtualenvs/deploy/local/lib/python2.7/site-packages/haystack/views.py", line 49, in __call__
return self.create_response()
File "/home/deploy/.virtualenvs/deploy/local/lib/python2.7/site-packages/haystack/views.py", line 129, in create_response
(paginator, page) = self.build_page()
File "/home/deploy/.virtualenvs/deploy/local/lib/python2.7/site-packages/haystack/views.py", line 106, in build_page
self.results[start_offset:start_offset + self.results_per_page]
File "/home/deploy/.virtualenvs/deploy/local/lib/python2.7/site-packages/haystack/query.py", line 266, in __getitem__
self._fill_cache(start, bound)
File "/home/deploy/.virtualenvs/deploy/local/lib/python2.7/site-packages/haystack/query.py", line 164, in _fill_cache
results = self.query.get_results(**kwargs)
File "/home/deploy/.virtualenvs/deploy/local/lib/python2.7/site-packages/haystack/backends/__init__.py", line 485, in get_results
self.run(**kwargs)
File "/home/deploy/.virtualenvs/deploy/local/lib/python2.7/site-packages/haystack/backends/elasticsearch_backend.py", line 942, in run
results = self.backend.search(final_query, **search_kwargs)
File "/home/deploy/.virtualenvs/deploy/local/lib/python2.7/site-packages/haystack/backends/__init__.py", line 26, in wrapper
return func(obj, query_string, *args, **kwargs)
File "/home/deploy/.virtualenvs/deploy/local/lib/python2.7/site-packages/haystack/backends/elasticsearch_backend.py", line 521, in search
distance_point=kwargs.get('distance_point'), geo_sort=geo_sort)
File "/home/deploy/.virtualenvs/deploy/local/lib/python2.7/site-packages/haystack/backends/elasticsearch_backend.py", line 571, in _process_results
raw_suggest = raw_results['suggest']['suggest']
KeyError: 'suggest'
A curious fact: the problem occurs only when the project is under production settings, even when I haven't changed a single thing involving Haystack or Elasticsearch in the settings_production module(except for the URL key).
project/settings_production.py
'URL': 'http://0.0.0.0:9200/'
In production, I'm using nothing more than a simple FastCGI.
And here's what really bothers me: sometimes I get no errors on this view, and everything works just fine...
Please, someone has an idea of what's going on?
Thanks a lot!
UPDATE:
SO, I setup my whole project in another computer. After some tests I verified:
this problem is not related to my production settings like I
described above;
the error is not raised when the elasticsearch service is stopped;
if the service is running:
when the method Object.objects.all() returns some QuerySet results, I got no errors;
when the method Object.objects.all() returns an empty QuerySet, the problem persists;
I guess this is some kind of bug in the Haystack's elasticsearch_backend module.
Still, i'm not sure.
Yup, it's a bug in haystack. I've put in a pull request, but in the meantime, options to get running are:
Set INCLUDE_SPELLING in your haystack settings to False, or
Use our fork: https://github.com/greenkahuna/django-haystack