Advertisement
Guest User

Untitled

a guest
Apr 27th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.91 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. import os
  3. import sys
  4. import populate
  5. from flask import g
  6. from flask import Flask, current_app
  7. from flask import render_template, request, jsonify
  8. import pymysql
  9.  
  10.  
  11. app = Flask(__name__)
  12. username = "root"
  13. password = "root"
  14. database = "hw4_ex3"
  15.  
  16. ## This method returns a list of messages in a json format such as
  17. ## [
  18. ##  { "name": <name>, "message": <message> },
  19. ##  { "name": <name>, "message": <message> },
  20. ##  ...
  21. ## ]
  22. ## If this is a POST request and there is a parameter "name" given, then only
  23. ## messages of the given name should be returned.
  24. ## If the POST parameter is invalid, then the response code must be 500.
  25. @app.route("/messages",methods=["GET","POST"])
  26. def messages():
  27.     if(request.method == 'GET'):
  28.         #app.logger.error("Get all messages! ")
  29.         res = get_all_messages(db)
  30.         return jsonify(res), 200
  31.  
  32.     elif(request.method == 'POST'):
  33.         json = []
  34.         req = request.get_json()
  35.         #app.logger.error("Post with json request: ")
  36.         #app.logger.error(req)
  37.  
  38.         # for empty req return all messages
  39.         if(req is None):
  40.             #app.logger.error("Empty req ")
  41.             #app.logger.error(req)
  42.             # it checks this!!!
  43.             #res = get_all_messages(db)
  44.             #return jsonify(res), 200
  45.             return ('', 500)
  46.  
  47.  
  48.         #app.logger.error("Non-empty req ")
  49.         #app.logger.error(req)
  50.  
  51.         name = ''
  52.         if 'name' in req:
  53.             name = req['name']
  54.         else:
  55.             return  ('', 500)
  56.  
  57.         # for empty name get all messages
  58.         if(name is None or name==''):
  59.             res = get_all_messages(db)
  60.             return jsonify(res), 200
  61.        
  62.         # non-empty name
  63.         app.logger.error("Non-empty name ", name)
  64.  
  65.         json = []
  66.         if ';' in name or '\'' in name:
  67.             #app.logger.error("SQL injection tried!")
  68.             return  ('', 500)
  69.  
  70.         with db.cursor() as cursor:
  71.             sql = "SELECT * FROM messages WHERE name=%s ;"
  72.             #cursor.execute(sql, ("%" + name+ "%"))
  73.             cursor.execute(sql, (name))
  74.             numrows = cursor.rowcount
  75.             if numrows==0:
  76.                 return ('', 200)
  77.  
  78.             for i in range(0,numrows):
  79.                 row = cursor.fetchone()
  80.                 json.append({'name': row[0], 'message': row[1]})
  81.  
  82.             return jsonify(json),200
  83.  
  84.         return  ('', 200)
  85.  
  86. def get_all_messages(db):
  87.     json = []
  88.     with db.cursor() as cursor:
  89.         cursor.execute("SELECT * FROM messages")
  90.         numrows = cursor.rowcount
  91.         for i in range(0,numrows):
  92.             row = cursor.fetchone()
  93.             json.append({'name': row[0], 'message': row[1]})
  94.  
  95.     return json
  96.  
  97.  
  98. ## This method returns the list of users in a json format such as
  99. ## { "users": [ <user1>, <user2>, ... ] }
  100. ## This methods should limit the number of users if a GET URL parameter is given
  101. ## named limit. For example, /users?limit=4 should only return the first four
  102. ## users.
  103. ## If the paramer given is invalid, then the response code must be 500.
  104. @app.route("/users",methods=["GET"])
  105. def contact():
  106.     with db.cursor() as cursor:
  107.         json = []
  108.         limit = request.args.get('limit')
  109.         users = []
  110.         print('Get data for parameter ', limit)
  111.  
  112.         if(limit is None or limit==''):
  113.             cursor.execute("SELECT * FROM users")
  114.             numrows = cursor.rowcount
  115.             for i in range(0,numrows):
  116.                 row = cursor.fetchone()
  117.                 users.append(row[1])
  118.  
  119.             json = {'users': users}  
  120.             return jsonify(json), 200
  121.        
  122.         try:
  123.             print('limit ', limit)
  124.  
  125.             if('-' in limit):
  126.                 return ('',500)
  127.  
  128.             if limit.isdigit():
  129.                 print('limit is digit')
  130.                 limit = int(limit)
  131.             else:
  132.                 return ('',500)
  133.            
  134.             if(limit<0):
  135.                 return ('',500)
  136.  
  137.             cursor.execute("SELECT * FROM users")
  138.             numrows = cursor.rowcount
  139.             if limit is None:
  140.                 it = numrows
  141.             else:
  142.                 it = limit if limit<numrows else numrows
  143.  
  144.             for i in range(0,it):
  145.                 row = cursor.fetchone()
  146.                 users.append(row[1])
  147.  
  148.             json = {'users': users}  
  149.             return jsonify(json), 200
  150.  
  151.         except ValueError:
  152.             print('Should be number!')
  153.  
  154.         return jsonify(json),500
  155.  
  156.  
  157.  
  158.  
  159. if __name__ == "__main__":
  160.     seed = "randomseed"
  161.     if len(sys.argv) == 2:
  162.         seed = sys.argv[1]
  163.  
  164.     db = pymysql.connect("localhost",
  165.                 username,
  166.                 password,
  167.                 database)
  168.     with db.cursor() as cursor:
  169.         populate.populate_db(seed,cursor)            
  170.         db.commit()
  171.     print("[+] database populated")
  172.  
  173.     app.run(host='0.0.0.0',port=80)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement