Html Mysql Upload and Store Image Python Flask

The Cloudera Operational Database (COD) is a managed dbPaaS solution available as an experience in Cloudera Information Platform (CDP). It offers multi-modal client access with NoSQL key-value using Apache HBase APIs and relational SQL with JDBC (via Apache Phoenix). The latter makes COD accessible to developers who are used to edifice applications that use MySQL, Postgres, etc . Main benefits of COD include:

  • Automobile-scaling –  based on the workload utilization of the cluster and will soon have the ability to scale up/downwards the cluster
  • Machine-melody – amend performance within the existing infrastructure footprint.
  • Auto-heal – resolve operational problems automatically (coming soon).

In this weblog, I will demonstrate how COD can easily be used as a backend system to shop data and images for a simple spider web awarding. To build this application, we volition be using Phoenix, one of the underlying components of COD, along with Flask. For storing images, nosotros volition be using an HBase (Apache Phoenix backend storage) capability called MOB (medium objects). MOB allows the states to read/write values from 100k-10MB quickly.

*For development ease of use, you tin too use the Phoenix query server instead of COD. The query server is a small-scale build of phoenix that is meant for development purposes only, and data is deleted in each build.

All code is in my github repo .

Instructions:

1. Log in to Cloudera Management Console and select the Operational Database experience

Login OpDB

two. Choose your environment and name your DB

OpDB 2

3. Once the DB is upwards, take the URL from the sparse JDBC client

iv. Set up your CDP workload password

5. Clone project git repo and install requirements: $ pip install -r requirements.txt

6. Get to app binder and run "setup.py" – this will create a table with iii records of users and their images $ python setup.py

7. Run the flask spider web server for the web awarding to start: $ FLASK_APP=app.py python -m flask run –port=8888 –host=127.0.0.ane  –reload –with-threads –debugger

viii. Go to http://localhost:8888/users on your browser. Yous should be able to see the application running! Simple as that.

Going through The Lawmaking

1. The Schema class,  Basically holds the connection details and create and drop table methods. As you tin can see, the "photo" cavalcade is a VARBINARY type, which translate to an MOB object in HBase:

                      import phoenixdb                                import phoenixdb.cursor                                class Schema:                                              def __init__(self):                                              opts = {}                                              opts['authentication'] = 'BASIC'                                        opts['avatica_user'] = '                                <cod workload username>                                '                                        opts['avatica_password'] = '                                <cod workload pw>                                '                                        database_url = "                                <cod thin jdbc url>                                "                                              cocky.TABLENAME = "users"                                              self.conn = phoenixdb.connect(database_url, autocommit=True,**opts)                                        self.curs = cocky.conn.cursor()                                              def create_users_table(self):                                              query = """                                              CREATE Table IF NOT EXISTS """+self.TABLENAME+""" (                                              username VARCHAR NOT NULL,                                              firstname VARCHAR,                                              lastname  VARCHAR,                                              telephone VARCHAR,                                              message VARCHAR,                                              electronic mail VARCHAR,                                              photo VARBINARY,                                              photo_name VARCHAR,                                              photo_type VARCHAR,                                              photo_chars VARCHAR                                              CONSTRAINT my_pk Main Cardinal (username))                                              """                                        self.curs.execute(query)                                              def drop_users_table(self):                                              query = "DROP TABLE "+cocky.TABLENAME                                        self.curs.execute(query)                  

2 The users class is responsible for all application operations with Phoenix. Nosotros can update/insert (upsert in phoenix linguistic communication) , delete, list , and handle images transactions:

                      import phoenixdb                                from schema import Schema                                import json                                course UsersModel:                                    TABLENAME = "users"                                              def __init__(self):                                              db = Schema()                                              cocky.conn=db.conn                                        self.curs=db.curs                                    def upsert(self, params):                                              sql = "upsert into " + cocky.TABLENAME + \                                              " (username ,message,phone,firstname,lastname,email) \                                              values (?,?,?,?,?,?)"                                              information = (params.get('username'),params.get('message'),\                                              params.get('phone'),params.become('firstname'),\                                              params.go('lastname'),params.become('email'))                                              results = self.curs.execute(sql,data)                                        return results                                              def upsert_photo(cocky, params):                                              if params.get('photo') is None:                                              photo = bytes('','utf-eight')                                              else:                                            photo = params.get('photo')                                              sql = "upsert into " + self.TABLENAME + \                                            " (username, photograph,photo_name) values (?,?,?)"                                              data = (params.get('username'),photo, params.go('photo_name'))                                              results = cocky.curs.execute(sql,data)                                        return results                                              def delete(self, username):                                              query = f"DELETE from {self.TABLENAME} " \                                                f"WHERE username = {username}"                                        self.curs.execute(query)                                              def list_items(self, where_clause="",format="json"):                                              query = f"SELECT username ,email,message,telephone,firstname,\                                              lastname,photo_name " \                                            f"from {self.TABLENAME} WHERE  " + where_clause                                              self.curs.execute(query)                                              if format=="json":                                              r = [dict((self.curs.description[i][0].lower(), value) \                                              for i, value in enumerate(row)) for row in \                                              self.curs.fetchall()]                                              self.conn.close()                                              data={'data': r }                                              return json.dumps(data)                                                          result_set=cocky.curs.fetchall()                                              consequence = [{cavalcade: row[i]                                              for i, column in enumerate(result_set[0].keys())}                                              for row in result_set]                                              return result                                              def get_image(cocky, username):                                              query = f"SELECT photograph,photo_name " \                                                f"from {self.TABLENAME} WHERE  username='"+username+"'"                                              cocky.curs.execute(query)                                              row = self.curs.fetchone()                                              return row                  

3. The app.py is the master router for the application. It contains all handling with user inputs and routing them to the connect methods. I separated the treatment of images for the ease of use, and that way i can go a specific prototype for a user:

                      from flask import Flask, request, send_file ,jsonify,render_template                                import phoenixdb                                import io                                from users import UsersModel                                from schema import Schema                                import json                                            app = Flask(__name__)                                            @app.after_request                                def add_headers(response):                                              response.headers['Access-Control-Allow-Origin'] = '*'                                              response.headers['Access-Control-Allow-Headers'] =  \                                              "Content-Type, Access-Command-Permit-Headers, Authorization, \                                              X-Requested-With"                                              response.headers['Access-Control-Let-Methods']=  "Post, Go, PUT, \                                              DELETE, OPTIONS"                                              response.headers['Allow']=  "Mail, GET, PUT, OPTIONS"                                    return response                                @app.route("/")                                def how-do-you-do():                                    return "Hello World!"                                @app.route("/users")                                def return_form():                                    return render_template("users.html")                                @app.road("/handle_data",methods=['POST'])                                def handle_data():                                              if request.method == 'POST':                                              username = request.class['username']                                              firstname = request.form['firstname']                                              lastname = request.form['lastname']                                              electronic mail = request.form['e-mail']                                              telephone = request.form['telephone']                                              message = request.class['bulletin']                                              photo = request.files['photograph']                                              photo_bytes = photograph.read()                                              model=Schema()                                              usersmodel=UsersModel()                                              data = {'username':f"{username}",'firstname':f"{firstname}",\                                              'lastname':f"{lastname}",'phone':f"{telephone}",\                                              'bulletin':f"{message}"}                                              photo_data = {'username':f"{username}",\                                              'photo':photo_bytes,\                                              'photo_name':f"{photograph.filename}"}                                              usersmodel.upsert(data)                                              usersmodel.upsert_photo(photo_data)                                              render render_template('users.html')                                              else:                                        return render_template('users.html')                                @app.road("/get_users",methods=['GET'])                                def get_users():                                              if request.method == 'GET':                                              usersmodel=UsersModel()                                              users = usersmodel.list_items("1=i")                                        return users                                @app.route("/get_image",methods=['GET'])                                def get_image():                                              if request.method == 'Get':                                              username = request.args.get('username')                                              usersmodel=UsersModel()                                              imagedb = usersmodel.get_image(username)                                              return send_file(io.BytesIO(imagedb[0]),mimetype='image/png', \                                              attachment_filename=imagedb[1])                                if __name__ == "__main__":                                              Schema()                                              app.run(debug=True, port=8888)                  

Next steps, yous tin can utilize this github repo to test your application.

Hope you find information technology useful, Happy coding!!

jacksonagothad.blogspot.com

Source: https://blog.cloudera.com/building-a-simple-crud-web-application-and-image-store-using-cloudera-operational-database-and-flask/

0 Response to "Html Mysql Upload and Store Image Python Flask"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel