HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

App for displaying pictures to like

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
picturesapplikedisplayingfor

Problem

I am making an app that shows some pictures and you can like each picture. I am sending a POST request from the Android device. In my backend I have a Python script that takes parameters category and URL of the picture, opens a JSON file, and modifies the "likes" value.

This is the Python script:

#!/usr/bin/python
# Import modules for CGI handling 
import cgi, cgitb, json

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Get data from fields
category= form.getvalue('category')
url= form.getvalue('url')

#Gets the file path,depending on the category
filepath='/home2/public_html/app/%s/%s.json' % (category,category)

# Open a file
with open(filepath) as data_file:    
data = json.load(data_file)

# Finds the picture with the specific url and updates the likes value.
for picture in data:
    if picture ["url"] == url:
        likes = int(picture["likes"])
        picture["likes"]=str(likes+1)
        break

# Writes the json file with the new value.
with open(filepath, 'w') as data_file:
    data_file.write(json.dumps(data))


My JSON looks like this:

{"url": "http://pictures.com/app/Funny/picture.jpg", "category": "Funny", "likes": "0"}


What can go wrong with this script? Are there any potential drawbacks? I am new to backend programming, so I don't know what can go wrong here.

Solution

I'm not sure what this program is trying to do, but I can give a few suggestions for style and improvements.

  • Firstly, unless you're not using the python command to run this script on the command line, you don't need the #!/usr/bin/python.



  • Secondly, I'd separate the imports out on each separate line like so.



import cgi
import cgitb
import json


  • This is in case an error occurs with the imports, if thats the case, the error will be easier to find.



  • After that I'd separate certain things into functions and add docstrings. A few things I might want to separate into functions is opening the file, updating the like values, and writing to the JSON file. This gives your program a bit of re-usability.



  • My final bit of advice would be to remove or improve un-needed comments such as the following.



# Create instance of FieldStorage
# Open a file
# Import modules for CGI handling


I'd also recommend checking out Python's style guide, PEP8. Hope this helps!

Code Snippets

import cgi
import cgitb
import json
# Create instance of FieldStorage
# Open a file
# Import modules for CGI handling

Context

StackExchange Code Review Q#86961, answer score: 3

Revisions (0)

No revisions yet.