def find_by_name(cls,name): query = "SELECT * FROM {table} WHERE name=%s".format(table=cls.TABLE_NAME) dbh=DB_Handler() result=dbh.execute_query_fetch_one(query,(name,)) if result: row= result if row: return cls(row[0],row[1])
def get(self): dbh = DB_Handler() query = "SELECT * FROM {table}".format(table=self.TABLE_NAME) try: result = dbh.execute_query(query) except: return {"message": "error getting items list"}, 500 items = [] for row in result: items.append({'name': row[0], 'price': row[1]}) if items: return {"items": items} return {'message': "No items found"}, 404
def get(self): dbh = DB_Handler() query = "SELECT * FROM {table}".format(table=self.TABLE_NAME) try: result = dbh.execute_query(query) except: return {"message": "error getting users list"}, 500 users = [] for row in result: users.append({'id': row[0], 'username': row[1]}) if users: return {"users": users} return {'message': "No users found"}, 404
def delete(self, name): item = ItemModel.find_by_name(name) if not item: return { "message": "The item with name {} doesn't exist".format(name) }, 400 query = "DELETE FROM {table} WHERE name=%s".format( table=self.TABLE_NAME) dbh = DB_Handler() try: dbh.execute_query(query, (name, )) except: return {"message": "Error deleting the entry"}, 500 return {"message": "item {} is deleted from items".format(name)}
def find_by_id(cls, _id): dbh= DB_Handler() query = "SELECT * FROM {table} WHERE id=%s".format(table=cls.TABLE_NAME) try: result = dbh.execute_query_fetch_one(query,(_id,)) except: return {"message":"Unable to exexute query to find by id"} row = result if row: user = cls(*row) else: user = None return user
def post(self): data = UserRegister.parser.parse_args() if UserModel.find_by_username(data['username']): return {"message": "User with this username already exists"}, 400 dbh = DB_Handler() query = "INSERT INTO {table} VALUES (NULL, %s, %s)".format( table=self.TABLE_NAME) try: dbh.execute_query(query, (data['username'], data['password'])) except Exception as e: print(e) return {"message": "Unable to register user"} return {"message": "User Created"}, 201
def create_app(test_config=None): """ Create the Flask application """ app = Flask(__name__, instance_relative_config=True) app.config.from_pyfile("config.py") # create database handler db = DB_Handler(app.config) # page routes: @app.route("/") def page_index(): """ Return the static main page. This page allows the user to create a gallery from uploaded images. """ return app.send_static_file("create.html") @app.route("/gallery/<id>") def page_gallery(id): """ Return a gallery view page. """ gallery = db.select_gallery(id) if gallery == None: abort(404) title = gallery["title"] date = gallery["date_created"] images = [db.select_image_metadata(id) for id in gallery["images"]] return render_template("gallery.html", title=title, date=date, images=images) # API routes: @app.route("/api/v1.0/upload", methods=["POST"]) def api_upload_image(): """ Upload an image. Request body must be json: { file: ... (REQUIED) (base64 encoded), description: ... (OPTIONAL) } """ if not request.json or "file" not in request.json: abort(400) # bad request try: id = db.insert_image(file=b64decode(request.json["file"]), description=request.json.get( "description", ""), date=datetime.now(), uploader_ip=request.remote_addr) return make_response(jsonify({"id": id}), 201) # created except Exception as e: return make_response( jsonify({ "error": "Failed to upload image", "details": str(e) }), 500) @app.route("/api/v1.0/image/<id>", methods=["GET"]) def api_get_image(id): """ Retrieve an image by its ID Returns json response { id, file, description, upload_date } """ try: data = db.select_image(id) data["file"] = b64encode( data["file"]).decode() # encode as b64 then convert to string if data == None: abort(404) return make_response(jsonify(data), 200) except Exception as e: return make_response( jsonify({ "error": "Failed to get image", "details": str(e) }), 500) @app.route("/api/v1.0/image/<id>.<ext>", methods=["GET"]) def api_get_image_raw(id, ext): """ Retrieve an image by its ID Return only the file itself ext should be 'jpg' but can be anything. If it's wrong that's the browser's problem (Imgur does this, too) """ try: data = db.select_image(id) if data == None: abort(404) return send_file(BytesIO(data["file"]), attachment_filename=f"{id}.{ext}") except Exception as e: return make_response( jsonify({ "error": "Failed to get image", "details": str(e) }), 500) @app.route("/api/v1.0/gallery/create", methods=["POST"]) def api_create_gallery(): """ Create an image gallery Request body must be json: { title: ... (OPTIONAL), images: ... (OPTIONAL) (an image is an image ID) } """ if not request.json: abort(400) # bad request try: id = db.insert_gallery(title=request.json.get("title", ""), date=datetime.now(), images=request.json.get("images", []), uploader_ip=request.remote_addr) return make_response(jsonify({"id": id}), 201) # created except Exception as e: return make_response( jsonify({ "error": "Failed to upload image", "details": str(e) }), 500) return app
def update(self): dbh = DB_Handler() query = "UPDATE {table} SET price=%s WHERE name=%s".format(table=self.TABLE_NAME) dbh.execute_query(query,(self.price,self.name))
def insert(self): query = "INSERT INTO {table} VALUES(%s,%s)".format(table=self.TABLE_NAME) dbh=DB_Handler() dbh.execute_query(query, (self.name,self.price))
import MySQLdb import os from db import DB_Handler dbh = DB_Handler() DATABASE_NAME = 'flask_rest_db' # create_database="CREATE DATABASE IF NOT EXISTS {db_name}".format(db_name=DATABASE_NAME) # dbh.execute_query(create_database) create_table = "CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(80) UNIQUE, password VARCHAR(100))" dbh.execute_query(create_table) # user = (1, 'bob', '123') # insert_query= "INSERT INTO users VALUES (?,?)" # cursor.execute(insert_query, user) create_table = "CREATE TABLE IF NOT EXISTS items (name VARCHAR(150) UNIQUE PRIMARY KEY, price float)" dbh.execute_query(create_table) # dbh.execute_query("INSERT INTO items VALUES (?,?)",('laptop','700'))