Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- import os
- import sys
- import populate
- from flask import g
- from flask import Flask, current_app
- from flask import render_template, request, jsonify
- import pymysql
- app = Flask(__name__)
- username = "root"
- password = "root"
- database = "hw4_ex3"
- ## This method returns a list of messages in a json format such as
- ## [
- ## { "name": <name>, "message": <message> },
- ## { "name": <name>, "message": <message> },
- ## ...
- ## ]
- ## If this is a POST request and there is a parameter "name" given, then only
- ## messages of the given name should be returned.
- ## If the POST parameter is invalid, then the response code must be 500.
- @app.route("/messages",methods=["GET","POST"])
- def messages():
- if(request.method == 'GET'):
- #app.logger.error("Get all messages! ")
- res = get_all_messages(db)
- return jsonify(res), 200
- elif(request.method == 'POST'):
- json = []
- req = request.get_json()
- #app.logger.error("Post with json request: ")
- #app.logger.error(req)
- # for empty req return all messages
- if(req is None):
- #app.logger.error("Empty req ")
- #app.logger.error(req)
- # it checks this!!!
- #res = get_all_messages(db)
- #return jsonify(res), 200
- return ('', 500)
- #app.logger.error("Non-empty req ")
- #app.logger.error(req)
- name = ''
- if 'name' in req:
- name = req['name']
- else:
- return ('', 500)
- # for empty name get all messages
- if(name is None or name==''):
- res = get_all_messages(db)
- return jsonify(res), 200
- # non-empty name
- app.logger.error("Non-empty name ", name)
- json = []
- if ';' in name or '\'' in name:
- #app.logger.error("SQL injection tried!")
- return ('', 500)
- with db.cursor() as cursor:
- sql = "SELECT * FROM messages WHERE name=%s ;"
- #cursor.execute(sql, ("%" + name+ "%"))
- cursor.execute(sql, (name))
- numrows = cursor.rowcount
- if numrows==0:
- return ('', 200)
- for i in range(0,numrows):
- row = cursor.fetchone()
- json.append({'name': row[0], 'message': row[1]})
- return jsonify(json),200
- return ('', 200)
- def get_all_messages(db):
- json = []
- with db.cursor() as cursor:
- cursor.execute("SELECT * FROM messages")
- numrows = cursor.rowcount
- for i in range(0,numrows):
- row = cursor.fetchone()
- json.append({'name': row[0], 'message': row[1]})
- return json
- ## This method returns the list of users in a json format such as
- ## { "users": [ <user1>, <user2>, ... ] }
- ## This methods should limit the number of users if a GET URL parameter is given
- ## named limit. For example, /users?limit=4 should only return the first four
- ## users.
- ## If the paramer given is invalid, then the response code must be 500.
- @app.route("/users",methods=["GET"])
- def contact():
- with db.cursor() as cursor:
- json = []
- limit = request.args.get('limit')
- users = []
- print('Get data for parameter ', limit)
- if(limit is None or limit==''):
- cursor.execute("SELECT * FROM users")
- numrows = cursor.rowcount
- for i in range(0,numrows):
- row = cursor.fetchone()
- users.append(row[1])
- json = {'users': users}
- return jsonify(json), 200
- try:
- print('limit ', limit)
- if('-' in limit):
- return ('',500)
- if limit.isdigit():
- print('limit is digit')
- limit = int(limit)
- else:
- return ('',500)
- if(limit<0):
- return ('',500)
- cursor.execute("SELECT * FROM users")
- numrows = cursor.rowcount
- if limit is None:
- it = numrows
- else:
- it = limit if limit<numrows else numrows
- for i in range(0,it):
- row = cursor.fetchone()
- users.append(row[1])
- json = {'users': users}
- return jsonify(json), 200
- except ValueError:
- print('Should be number!')
- return jsonify(json),500
- if __name__ == "__main__":
- seed = "randomseed"
- if len(sys.argv) == 2:
- seed = sys.argv[1]
- db = pymysql.connect("localhost",
- username,
- password,
- database)
- with db.cursor() as cursor:
- populate.populate_db(seed,cursor)
- db.commit()
- print("[+] database populated")
- app.run(host='0.0.0.0',port=80)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement