Skip to content

Commit

Permalink
Merge pull request #3 from smathot/master
Browse files Browse the repository at this point in the history
Make Unicode safe
  • Loading branch information
dschreij committed Apr 27, 2016
2 parents 2f6945b + aa8ce9d commit 0135ff9
Show file tree
Hide file tree
Showing 5 changed files with 75 additions and 89 deletions.
8 changes: 7 additions & 1 deletion QOpenScienceFramework/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
__version__ = "1.0.3"
__author__ = "Daniel Schreij"

import os
import sys
from QOpenScienceFramework.compat import *
dirname = safe_decode(os.path.dirname(__file__),
enc=sys.getfilesystemencoding())

import QOpenScienceFramework.connection
import QOpenScienceFramework.manager
import QOpenScienceFramework.widgets
import QOpenScienceFramework.widgets
14 changes: 5 additions & 9 deletions QOpenScienceFramework/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from QOpenScienceFramework.compat import *

# Import basics
import os
Expand All @@ -27,9 +28,10 @@
from oauthlib.oauth2 import MobileApplicationClient
# Easier function decorating
from functools import wraps
from QOpenScienceFramework import dirname

# Load settings file containing required OAuth2 parameters
with open(os.path.join(os.path.dirname(__file__), 'settings.json')) as fp:
with open(os.path.join(dirname, 'settings.json')) as fp:
settings = json.load(fp)
base_url = settings['base_url']
api_base_url = settings['api_base_url']
Expand All @@ -49,7 +51,7 @@ class OSFInvalidResponse(Exception):
def create_session():
""" Creates/resets and OAuth 2 session, with the specified data. """
global session
global settings
global settings

try:
client_id = settings['client_id']
Expand Down Expand Up @@ -107,7 +109,7 @@ def check_for_active_session():
if session is None:
raise RuntimeError("Session is not yet initialized, use connection."
"session = connection.create_session()")


#%%--------------------------- Oauth communiucation ----------------------------

Expand Down Expand Up @@ -256,9 +258,3 @@ def direct_api_call(api_call):

if __name__ == "__main__":
print(get_authorization_url())






7 changes: 4 additions & 3 deletions QOpenScienceFramework/loginwindow.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,9 @@
import QOpenScienceFramework.connection as osf
# Python 2 and 3 compatiblity settings
from QOpenScienceFramework.compat import *
from QOpenScienceFramework import dirname

osf_logo_path = os.path.join(os.path.dirname(__file__), 'img/cos-white2.png')
osf_logo_path = os.path.join(dirname, 'img/cos-white2.png')

# Dummy function later to be replaced for translation
_ = lambda s: s
Expand Down Expand Up @@ -96,7 +97,7 @@ def checkResponse(self, reply):
self.token = osf.parse_token_from_url(r_url)
except ValueError as e:
logging.warning(e)
else:
else:
self.logged_in.emit()
self.hide()

Expand All @@ -117,6 +118,6 @@ def check_URL(self, url):
self.token = osf.parse_token_from_url(url_string)
except ValueError as e:
logging.warning(e)
else:
else:
self.logged_in.emit()
self.hide()
43 changes: 21 additions & 22 deletions QOpenScienceFramework/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,9 +198,9 @@ def check_for_stored_token(self, tokenfile):
def check_network_accessibility(func):
""" Decorator function, not to be called directly.
Checks if network is accessible and buffers the network request so
that it can be sent again if it fails the first time, due to an invalidated
OAuth2 token. In this case the user will be presented with the login
screen again. If the same user successfully logs in again, the request
that it can be sent again if it fails the first time, due to an invalidated
OAuth2 token. In this case the user will be presented with the login
screen again. If the same user successfully logs in again, the request
will be resent. """

@wraps(func)
Expand All @@ -220,7 +220,7 @@ def func_wrapper(inst, *args, **kwargs):
# Add tuple with current user, and request to be performed
# to the pending request dictionary
inst.pending_requests[request_id] = (
inst.logged_in_user['data']['id'],
inst.logged_in_user['data']['id'],
current_request)
# Add current request id to kwargs of function being called
kwargs['_request_id'] = request_id
Expand Down Expand Up @@ -271,7 +271,7 @@ def __check_request_parameters(self, url, callback):
if not isinstance(url, QtCore.QUrl) and not isinstance(url, basestring):
raise TypeError("url should be a string or QUrl object")
if not isinstance(url, QtCore.QUrl):
url = get_QUrl(url)
url = QtCore.QUrl(url)
if not callable(callback):
raise TypeError("callback should be a function or callable.")
return url
Expand Down Expand Up @@ -322,7 +322,7 @@ def get(self, url, callback, *args, **kwargs):
if not self.add_token(request):
self.warning_message.emit('Warning',
_(u"Token could not be added to the request"))

# Check if this is a redirect and keep a count to prevent endless
# redirects. If redirect_count is not set, init it to 0
kwargs['redirect_count'] = kwargs.get('redirect_count',0)
Expand Down Expand Up @@ -681,10 +681,10 @@ def download_file(self, url, destination, *args, **kwargs):
kwargs['destination'] = destination
kwargs['download_url'] = url
# Extra call to get() to make sure OAuth2 token is still valid before download
# is initiated. If not, this way the request can be repeated after the user
# is initiated. If not, this way the request can be repeated after the user
# reauthenticates
self.get_logged_in_user(self.__download, *args, **kwargs)

def upload_file(self, url, source_file, *args, **kwargs):
""" Upload a file to the specified destination on the OSF
Expand Down Expand Up @@ -716,7 +716,7 @@ def upload_file(self, url, source_file, *args, **kwargs):
Any other keywoard arguments that you want to have passed to the callback
"""
# Extra call to get() to make sure OAuth2 token is still valid before download
# is initiated. If not, this way the request can be repeated after the user
# is initiated. If not, this way the request can be repeated after the user
# reauthenticates
kwargs['upload_url'] = url
kwargs['source_file'] = source_file
Expand All @@ -730,7 +730,7 @@ def __reply_finished(self, callback, *args, **kwargs):
# Get the error callback function, if set
errorCallback = kwargs.get('errorCallback', None)
# Get the request id, if set (only for authenticated requests, if a user
# is logged in), so it can be repeated if the user is required to
# is logged in), so it can be repeated if the user is required to
# reauthenticate.
current_request_id = kwargs.pop('_request_id', None)

Expand Down Expand Up @@ -794,7 +794,7 @@ def __reply_finished(self, callback, *args, **kwargs):
return
# Perform another request with the redirect_url and pass on the callback
redirect_url = reply.attribute(request.RedirectionTargetAttribute)
# For now, the redirects only work for GET operations (but to my
# For now, the redirects only work for GET operations (but to my
# knowledge, those are the only operations they occur for)
if reply.operation() == self.GetOperation:
self.get(redirect_url, callback, *args, **kwargs)
Expand All @@ -813,8 +813,8 @@ def __reply_finished(self, callback, *args, **kwargs):
reply.deleteLater()

def __create_progress_dialog(self, text, filesize):
""" Creates a progress dialog
""" Creates a progress dialog
Parameters
----------
text : str
Expand All @@ -838,7 +838,7 @@ def __transfer_progress(self, transfered, total):
self.sender().property('progressDialog').setValue(transfered)

def __download(self, reply, download_url, *args, **kwargs):
""" The real download function, that is a callback for get_logged_in_user()
""" The real download function, that is a callback for get_logged_in_user()
in download_file() """
# Create tempfile
tmp_file = QtCore.QTemporaryFile()
Expand All @@ -858,11 +858,11 @@ def __download(self, reply, download_url, *args, **kwargs):

# Callback function for when bytes are received
kwargs['readyRead'] = self.__download_readyRead
# Download the file with a get request
# Download the file with a get request
self.get(download_url, self.__download_finished, *args, **kwargs)

def __download_readyRead(self, *args, **kwargs):
""" callback for a reply object to indicate that data is ready to be
""" callback for a reply object to indicate that data is ready to be
written to a buffer. """

reply = self.sender()
Expand Down Expand Up @@ -912,7 +912,6 @@ def __upload(self, reply, upload_url, source_file, *args, **kwargs):
""" Callback for get_logged_in_user() in upload_file(). Does the real
uploading. """
# Put checks for the url to be a string or QUrl

# Check source file
if isinstance(source_file, basestring):
# Check if the specified file exists, because a situation is possible in which
Expand Down Expand Up @@ -941,7 +940,7 @@ def __upload(self, reply, upload_url, source_file, *args, **kwargs):
kwargs['uploadProgress'] = self.__transfer_progress

source_file.open(QtCore.QIODevice.ReadOnly)
self.put(upload_url, self.__upload_finished, data_to_send=source_file,
self.put(upload_url, self.__upload_finished, data_to_send=source_file,
*args, **kwargs)

def __upload_finished(self, reply, *args, **kwargs):
Expand All @@ -950,7 +949,7 @@ def __upload_finished(self, reply, *args, **kwargs):
progressDialog = kwargs.pop('progressDialog', None)
if isinstance(progressDialog, QtWidgets.QWidget):
progressDialog.deleteLater()
if not 'data_to_send' in kwargs or not isinstance(kwargs['data_to_send'],
if not 'data_to_send' in kwargs or not isinstance(kwargs['data_to_send'],
QtCore.QIODevice):
raise AttributeError("No valid open file handle")
# Close the source file
Expand All @@ -963,13 +962,13 @@ def __upload_finished(self, reply, *args, **kwargs):

def __close_file_handles(self, *args, **kwargs):
""" Closes any open file handles after a failed transfer. Called by
__reply_finished when a HTTP response code indicating an error has been
__reply_finished when a HTTP response code indicating an error has been
received """
# When a download is failed, close the file handle stored in tmp_file
tmp_file = kwargs.pop('tmp_file', None)
if isinstance(tmp_file, QtCore.QIODevice):
tmp_file.close()
# File uploads are stored in data_to_send
# File uploads are stored in data_to_send
data_to_send = kwargs.pop('data_to_send', None)
if isinstance(data_to_send, QtCore.QIODevice):
data_to_send.close()
Expand All @@ -992,4 +991,4 @@ def set_logged_in_user(self, user_data):
for (user_id, request) in self.pending_requests.values():
if user_id == self.logged_in_user['data']['id']:
request()
self.pending_requests = {}
self.pending_requests = {}
Loading

0 comments on commit 0135ff9

Please sign in to comment.