Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

do some cleaning and refactoring

  • Loading branch information...
commit 119fe5e0488f79c15c969e62b81756d62cae50b1 1 parent d42d628
@gelnior authored
View
19 auth/handlers.py
@@ -70,11 +70,10 @@ def post(self):
Get password via a json object. Sets a secure cookie if password
is OK. Else it returns an error response.
'''
- data = self.request.body
+ data = self.get_body_as_dict(expectedFields=["password"])
if data:
- postedData = json_decode(data)
- password = postedData["password"]
+ password = data["password"]
user = UserManager.getUser()
if user \
@@ -144,10 +143,10 @@ def post(self):
self.return_failure("Password is already set.")
else:
- data = self.request.body
+ data = self.get_body_as_dict(expectedFields=["password"])
if data:
- postedPassword = json_decode(data)['password']
+ postedPassword = data["password"]
if postedPassword and len(postedPassword) > 3:
password = \
@@ -199,12 +198,11 @@ def post(self):
self.return_failure("User already exists.")
else:
- data = self.request.body
+ data = self.get_body_as_dict(expectedFields=["name"])
if data:
- postedUser = json_decode(data)
user = User()
- user.name = postedUser['name']
+ user.name = data['name']
user.save()
user.key = user._id
user.save()
@@ -230,10 +228,11 @@ def put(self):
if user:
- data = self.request.body
+ data = self.get_body_as_dict(expectedFields=["password"])
+
if data:
- postedPassword = json_decode(data)['password']
+ postedPassword = data['password']
if postedPassword and len(postedPassword) >= 3:
user.password = \
View
72 contacts/handlers.py
@@ -28,21 +28,19 @@ def put(self):
received ones.
'''
- data = self.request.body
+ data = self.get_body_as_dict(["key", "url", "name", "description"])
if data:
- putContact = json_decode(data)
- key = putContact["key"]
+ key = data["key"]
contact = ContactManager.getTrustedContact(key)
if contact:
- contact.url = putContact["url"]
- contact.description = putContact["description"]
- contact.name = putContact["name"]
+ contact.url = data["url"]
+ contact.description = data["description"]
+ contact.name = data["name"]
contact.save()
self.create_modify_activity(contact, "modifies", "profile")
-
self.return_success("Contact successfully modified.")
else:
@@ -50,7 +48,7 @@ def put(self):
"No contact found corresponding to given contact", 404)
else:
- self.return_failure("Empty data.")
+ self.return_failure("Empty data or missing field.")
class ContactsPendingHandler(NewebeAuthHandler):
@@ -118,11 +116,8 @@ def get(self, slug):
contact = ContactManager.getContact(slug)
- if contact:
- self.return_document(contact)
+ self.return_one_document_or_404(contact, "Contact does not exist.")
- else:
- self.return_failure("Contact does not exist.", 404)
@asynchronous
def put(self, slug):
@@ -157,14 +152,12 @@ def on_contact_response(self, response, **kwargs):
'''
try:
- incomingData = response.body
- newebeResponse = json_decode(incomingData)
- if not newebeResponse["success"]:
- self.contact.state = STATE_ERROR
- self.contact.save()
- self.return_failure("Error occurs while confirming contact.")
- else:
- self.return_success("Contact trusted.")
+ incomingData = response.body
+ newebeResponse = json_decode(incomingData)
+ if not newebeResponse["success"]:
+ raise Exception()
+
+ self.return_success("Contact trusted.")
except:
self.contact.state = STATE_ERROR
self.contact.save()
@@ -211,11 +204,10 @@ def post(self):
logger = logging.getLogger("newebe.contact")
- data = self.request.body
+ data = self.get_body_as_dict(["url"])
if data:
- postedContact = json_decode(data)
- url = postedContact['url']
+ url = data["url"]
owner = UserManager.getUser()
if owner.url != url:
@@ -242,7 +234,7 @@ def post(self):
self.contact.state = STATE_ERROR
self.contact.save()
- return self.return_json(self.contact.toJson(), 201)
+ return self.return_one_document(self.contact, 201)
else:
return self.return_failure(
@@ -264,9 +256,9 @@ def on_contact_response(self, response, **kwargs):
self.contact.state = STATE_ERROR
self.contact.save()
- except Exception:
+ except:
import traceback
- logger.error("Error on adding contact:\n %s" %
+ logger.error("Error on adding contact, stacktrace :\n %s" %
traceback.format_exc())
self.contact.state = STATE_ERROR
@@ -311,7 +303,7 @@ def post(self, slug):
self.contact.state = STATE_ERROR
self.contact.save()
- self.return_json(self.contact.toJson(), 200)
+ self.return_one_document(self.contact)
else:
self.return_failure("Contact does not exist", 404)
@@ -340,14 +332,13 @@ def post(self):
Create a new contact from sent data (contact object at JSON format).
Sets its status to Wait For Approval
'''
- data = self.request.body
+ data = self.get_body_as_dict(expectedFields=["url"])
if data:
- postedContact = json_decode(data)
- url = postedContact["url"]
+ url = data["url"]
owner = UserManager.getUser()
- if url is not None and owner.url != url:
+ if owner.url != url:
slug = slugify(url)
contact = ContactManager.getContact(slug)
@@ -355,13 +346,13 @@ def post(self):
if contact is None:
contact = Contact(
- name = postedContact["name"],
+ name = data["name"],
url = url,
slug = slug,
- key = postedContact["key"],
+ key = data["key"],
state = STATE_WAIT_APPROVAL,
requestDate = datetime.datetime.utcnow(),
- description = postedContact["description"]
+ description = data["description"]
)
contact.save()
@@ -371,7 +362,7 @@ def post(self):
self.return_success("Request received.")
else:
- self.return_failure("Sent data are incorrects.")
+ self.return_failure("Contact and owner have same url.")
else:
self.return_failure("Sent data are incorrects.")
@@ -389,21 +380,18 @@ def post(self):
Updates contact from sent data (contact object at JSON format).
Sets its status to Trusted.
'''
- data = self.request.body
+ data = self.get_body_as_dict(expectedFields=["url", "key", "name"])
if data:
- postedContact = json_decode(data)
- url = postedContact["url"]
+ url = data["url"]
slug = slugify(url)
- key = postedContact["key"]
- name = postedContact["name"]
contact = ContactManager.getContact(slug)
if contact:
contact.state = STATE_TRUSTED
- contact.key = key
- contact.name = name
+ contact.key = data["key"]
+ contact.name = data["name"]
contact.save()
self.return_success("Contact trusted.")
View
24 core/handlers.py
@@ -53,6 +53,12 @@ def return_document(self, document, statusCode=200):
self.return_json(json_util.get_json_from_doc_list([document]),
statusCode)
+ def return_one_document(self, document, statusCode=200):
+ '''
+ Return document at JSON format.
+ '''
+
+ self.return_json(document.toJson(), statusCode)
def return_one_document_or_404(self, document, text):
'''
@@ -61,7 +67,7 @@ def return_one_document_or_404(self, document, text):
'''
if document:
- return self.return_json(document.toJson)
+ self.return_json(document.toJson())
else:
self.return_failure(text, 404)
@@ -107,15 +113,29 @@ def return_failure(self, text, statusCode=500):
self.return_json(json_encode({ "error" : text }), statusCode)
- def get_body_as_dict(self):
+ def get_document(self, get_doc, id):
+ doc = get_doc(id)
+
+ if doc:
+ return doc
+ else:
+ self.return_failure("Not found", 404)
+
+ def get_body_as_dict(self, expectedFields=[]):
'''
Return request body as a dict if body is written in JSON. Else None
is returned.
+ Return None if one given field is missing in the parsed dict.
'''
data = self.request.body
if data:
dataDict = json_decode(data)
+
+ for field in expectedFields:
+ if field not in dataDict:
+ return None
+
return dataDict
else:
return None
View
5 lib/http_util.py
@@ -38,7 +38,6 @@ def post(self, contact, path, body, callback=None):
'''
url = contact.url + path
-
request = HTTPRequest(url, method="POST", body=body,
validate_cert=False)
self.contacts[request] = contact
@@ -55,7 +54,6 @@ def put(self, contact, path, body, callback=None):
'''
url = contact.url + path
-
request = HTTPRequest(url, method="PUT", body=body,
validate_cert=False)
self.contacts[request] = contact
@@ -76,7 +74,6 @@ def post_files(self, contact, path, fields={}, files={}, callback=None):
headers = { 'Content-Type': contentType }
url = contact.url + path
-
request = HTTPRequest(url=url, method="POST",
body=body, headers=headers, validate_cert=False)
self.contacts[request] = contact
@@ -97,6 +94,7 @@ def delete(self, contact, path, body, extra=None):
request = HTTPRequest(url, method="PUT", body=body, validate_cert=False)
self.contacts[request] = contact
self.extra = extra
+
return self.client.fetch(request, self.on_contact_response)
@@ -112,7 +110,6 @@ def on_contact_response(self, response, **kwargs):
if response.error:
logger.error(""" Request to a contact failed, error infos
are stored inside activity.""")
-
self.activity.add_error(contact, extra=self.extra)
self.activity.save()
View
8 news/handlers.py
@@ -131,8 +131,8 @@ def post(self):
logger.info("Micropost post received.")
- data = self.get_body_as_dict()
- if data and "content" in data and data["content"]:
+ data = self.get_body_as_dict(expectedFields=["content"])
+ if data and data["content"]:
user = UserManager.getUser()
micropost = MicroPost(
@@ -169,9 +169,9 @@ def post(self):
are set from incoming data.
'''
- data = self.get_body_as_dict()
+ data = self.get_body_as_dict(expectedFields=["date", "authorKey"])
- if data and "date" in data and "authorKey" in data:
+ if data:
db_date = data.get("date")
date = date_util.get_date_from_db_date(db_date)
authorKey = data.get("authorKey")
View
7 notes/handlers.py
@@ -88,12 +88,7 @@ def get(self, noteid):
'''
note = NoteManager.get_note(noteid)
-
- if note:
- self.return_document(note)
-
- else:
- self.return_failure("No note exist for this id.", 404)
+ self.return_one_document_or_404(note, "No note exist for this id.")
def put(self, noteid):
View
16 profile/handlers.py
@@ -95,11 +95,9 @@ def get(self):
Retrieves current user (newebe owner) data at JSON format.
'''
- users = list()
user = UserManager.getUser()
- users.append(user)
- self.return_documents(users)
+ self.return_document(user)
def put(self):
@@ -110,20 +108,20 @@ def put(self):
user = UserManager.getUser()
- data = self.request.body
+ data = self.get_body_as_dict(
+ expectedFields=["name", "url", "description"])
if data:
- postedUser = json_decode(data)
- user.name = postedUser["name"]
- user.url = postedUser["url"]
- user.description = postedUser["description"]
+ user.name = data["name"]
+ user.url = data["url"]
+ user.description = data["description"]
user.save()
profile_updater.forward_profile()
self.return_success("User successfully Modified.")
else:
- self.return_failure("No data were sent.")
+ self.return_failure("Wrong data were sent.")
Please sign in to comment.
Something went wrong with that request. Please try again.