I am building a backend to a mobile application that will be hosted on a Django site connected to a PostgreSQL database.
I have never built anything to accomplish this before and this is my first go at it. I have not studied this type of application before so please let me know if the below code follows best practices for this task, is secure, and doesn't have any obvious problems. If there is an industry standard for this that is very different, please let me know what it is and why it is preferred.
My client connects via the view readJSON:
@csrf_exempt
def readJSON(request):
if request.method == 'POST':
try:
c = connections['postgres_db'].cursor()
json_data = json.loads(request.body)
if json_data['tag'] == 'register':
return HttpResponse(cc().register(c, json_data))
elif json_data['tag'] == 'syncprofile':
return HttpResponse(cc().syncProfile(c, json_data))
################ A long list of other possible tags
else:
raise Http404
finally:
c.close()
else:
raise Http404
I have a separate class that holds all the code to handle the incoming JSON requests. This is one such function.
def register(self, c, json_data):
import bcrypt as bc
salt = bc.gensalt()
pwrd = json_data['data']['password']
hash = bc.hashpw(pwrd, salt)
try:
c.execute("INSERT INTO profiles VALUES (DEFAULT, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
(json_data['data']['email'], hash, salt, json_data['data']['date_created'],
json_data['data']['state_lvl'], True,
json_data['data']['first_name'], json_data['data']['last_name'],
json_data['data']['sex'], json_data['data']['age'],
json_data['data']['state'], json_data['data']['country'],
json_data['data']['language'], json_data['data']['device_type'],
json_data['data']['device'], json_data['data']['device_width'],
json_data['data']['device_height'], json_data['data']['device_screen_density']
))
json_response = json.dumps({"success": 1, "errors": 0})
return HttpResponse(json_response, mimetype="application/json")
except Exception,e:
json_response = json.dumps({"success": 0, "errors": 1, "msg": str(e)})
return HttpResponse(json_response, mimetype="application/json")
And here is the JSON structure for the above function.
{
"tag":"register",
"data":{
"email":"[email protected]",
"password":"app123",
"date_created":"07/10/1967",
"state_lvl":"1",
"first_name":"John",
"last_name":"Smith",
"sex":"m",
"age":23,
"state":"CA",
"country":"USA",
"language":"english",
"device_type":"phone",
"device":"Nexus-5",
"device_width":400,
"device_height":800,
"device_screen_density":331
}
}