Advertisement
Guest User

Untitled

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