├── README.md ├── flask-cache ├── app.py ├── db.py ├── flask-cache.png ├── main.py ├── readme.rst └── templates │ └── index.html ├── flask-flash ├── main.py ├── readme.rst └── templates │ └── template.html ├── flask-multiple-files-upload ├── app.py ├── main.py ├── readme.rst └── templates │ └── upload.html ├── flask-reload-changes-without-server-restart ├── app.py ├── db.py ├── main.py ├── readme.rst └── templates │ └── index.html ├── flask-rest-mongodb ├── app.py ├── main.py └── readme.rst ├── google-charts └── pie-chart │ ├── app.py │ ├── main.py │ ├── readme.rst │ └── templates │ └── pie-chart.html ├── python-flask-ajax-file-upload ├── app.py ├── main.py ├── readme.rst └── templates │ └── file-upload.html ├── python-flask-ajax-mysql-login-logout ├── app.py ├── dao.py ├── db_config.py ├── main.py ├── readme.rst ├── rest.py ├── static │ └── js │ │ └── auth.js ├── templates │ ├── index.html │ └── login.html └── user.sql ├── python-flask-ajax-mysql-registration ├── app.py ├── dao.py ├── db_config.py ├── main.py ├── readme.rst ├── rest.py ├── static │ └── js │ │ └── register.js └── templates │ └── signup.html ├── python-flask-autocomplete-input-suggestion ├── app.py ├── data │ └── results.json ├── main.py ├── readme.rst └── templates │ └── autocomplete.html ├── python-flask-delete-multiple-rows-ajax-jquery-mysql ├── app.py ├── dao.py ├── db.py ├── main.py ├── product.sql ├── readme.rst ├── static │ ├── css │ │ └── table.css │ └── js │ │ └── app.js └── templates │ └── app.html ├── python-flask-file-download ├── app.py ├── html2pdf.pdf ├── info.xlsx ├── main.py ├── readme.rst ├── sample.txt ├── simple.docx └── templates │ └── download.html ├── python-flask-login-logout ├── app.py ├── db_config.py ├── main.py ├── readme.rst └── templates │ └── login.html ├── python-flask-mysql-ajax-username-availability-check ├── app.py ├── db_config.py ├── main.py ├── readme.rst ├── templates │ └── username.html └── user.sql ├── python-flask-mysql-crud ├── app.py ├── db_config.py ├── main.py ├── readme.rst ├── tables.py ├── templates │ ├── add.html │ ├── edit.html │ └── users.html └── user.sql ├── python-flask-mysql-jquery-ajax-multi-step-registration ├── app.py ├── db_config.py ├── main.py ├── readme.rst ├── templates │ └── multi-step-registration.html └── user.sql ├── python-flask-mysql-jquery-ajax-star-rating-system ├── app.py ├── dao.py ├── db_config.py ├── main.py ├── readme.rst ├── static │ ├── css │ │ └── blog_rating.css │ ├── img │ │ └── star.png │ └── js │ │ └── blog_rating.js └── templates │ └── star-rate-vote.html ├── python-flask-rest-api-file-upload ├── app.py ├── main.py └── readme.rst ├── python-flask-rest-api-multiple-files-upload ├── app.py ├── main.py └── readme.rst ├── python-flask-rest-api-multiple-response-formats ├── app.py ├── readme.rst └── rest.py ├── python-flask-rest-api-mysql-crud ├── app.py ├── db.py ├── main.py ├── readme.rst └── tbl_user.sql ├── python-flask-rest-api-query-param ├── app.py ├── db.py ├── readme.rst └── rest.py ├── python-flask-session ├── main.py ├── readme.rst └── templates │ └── template.html ├── python-flask-templates ├── app.py ├── main.py ├── readme.rst ├── static │ ├── css │ │ ├── contact.css │ │ └── main.css │ └── images │ │ ├── gentleman.png │ │ └── lady.png └── templates │ ├── about.html │ ├── contact.html │ ├── index.html │ ├── parent.html │ ├── products.html │ ├── snippets │ ├── footer.html │ ├── header.html │ └── left.html │ └── testimonials.html ├── python-flask-upload-display-image ├── app.py ├── main.py ├── readme.rst ├── static │ └── uploads │ │ └── sample.jpg └── templates │ └── upload.html ├── python-flask-upload-display-multiple-images ├── app.py ├── main.py ├── readme.rst ├── static │ └── uploads │ │ ├── nature-car.jpg │ │ └── sample.jpg └── templates │ └── upload.html ├── python-flask-upload-play-video ├── app.py ├── main.py ├── readme.rst ├── static │ └── uploads │ │ └── earth.mp4 └── templates │ └── upload.html ├── python_flask_file_upload ├── app.py ├── main.py ├── readme.rst └── templates │ └── upload.html └── python_flask_mysql_shopping_cart ├── app.py ├── db_config.py ├── main.py ├── readme.rst ├── static ├── css │ └── style.css └── images │ ├── icon-delete.png │ └── product-images │ ├── bag.jpg │ ├── camera.jpg │ ├── external-hard-drive.jpg │ ├── headphone.jpg │ ├── laptop.jpg │ ├── mobile.jpg │ ├── shoes.jpg │ └── watch.jpg └── templates └── products.html /README.md: -------------------------------------------------------------------------------- 1 | # flask 2 | This repository provides code examples on Python based Flask framework. 3 | -------------------------------------------------------------------------------- /flask-cache/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from flask_caching import Cache 3 | 4 | config = { 5 | "DEBUG": True, # run app in debug mode 6 | "CACHE_TYPE": "SimpleCache", # caching type 7 | "CACHE_DEFAULT_TIMEOUT": 300 # default Cache Timeout 8 | } 9 | 10 | app = Flask(__name__) 11 | 12 | # Flask to use the above defined config 13 | app.config.from_mapping(config) 14 | 15 | cache = Cache(app) -------------------------------------------------------------------------------- /flask-cache/db.py: -------------------------------------------------------------------------------- 1 | from app import app 2 | from flaskext.mysql import MySQL 3 | 4 | mysql = MySQL() 5 | 6 | # MySQL configurations 7 | app.config['MYSQL_DATABASE_USER'] = 'root' 8 | app.config['MYSQL_DATABASE_PASSWORD'] = 'root' 9 | app.config['MYSQL_DATABASE_DB'] = 'roytuts' 10 | app.config['MYSQL_DATABASE_HOST'] = 'localhost' 11 | 12 | mysql.init_app(app) -------------------------------------------------------------------------------- /flask-cache/flask-cache.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roytuts/flask/b5efbaf7d72c59765f0f29c18d9a83fde78e5d12/flask-cache/flask-cache.png -------------------------------------------------------------------------------- /flask-cache/main.py: -------------------------------------------------------------------------------- 1 | import pymysql 2 | from app import app 3 | from db import mysql 4 | from app import cache 5 | from flask import render_template 6 | 7 | @app.route('/') 8 | @cache.cached() 9 | #@cache.cached(timeout=50) 10 | def users(): 11 | conn = None 12 | cursor = None 13 | try: 14 | conn = mysql.connect() 15 | cursor = conn.cursor(pymysql.cursors.DictCursor) 16 | cursor.execute("SELECT * FROM user") 17 | rows = cursor.fetchall() 18 | print(rows) 19 | return render_template('index.html', rows=rows) 20 | except Exception as e: 21 | print(e) 22 | finally: 23 | if cursor: 24 | cursor.close() 25 | if conn: 26 | conn.close() 27 | 28 | if __name__ == "__main__": 29 | app.run() -------------------------------------------------------------------------------- /flask-cache/readme.rst: -------------------------------------------------------------------------------- 1 | Please follow the tutorial https://roytuts.com/python-flask-cache-in-web-applications/ 2 | -------------------------------------------------------------------------------- /flask-cache/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | Python Flask Simple Caching 3 |

Simple Caching in Flask

4 | 5 |
6 | {% for row in rows %} 7 |

Id: {{ row['id']|safe }}

8 |

Name: {{ row['name']|safe }}

9 |

Email: {{ row['email']|safe }}

10 |

Phone: {{ row['phone']|safe }}

11 |

Address: {{ row['address']|safe }}

12 | {% endfor %} 13 |

14 |

-------------------------------------------------------------------------------- /flask-flash/main.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, flash, render_template 2 | 3 | app = Flask(__name__) 4 | app.secret_key = "secret key" 5 | 6 | @app.route('/') 7 | def app_session(): 8 | flash('This is a flash error message', 'error') 9 | flash('This is a flash success message', 'success') 10 | return render_template('template.html') 11 | 12 | 13 | if __name__ == "__main__": 14 | app.run() 15 | -------------------------------------------------------------------------------- /flask-flash/readme.rst: -------------------------------------------------------------------------------- 1 | Please follow the tutorial https://roytuts.com/flash-message-management-in-python-flask/ 2 | -------------------------------------------------------------------------------- /flask-flash/templates/template.html: -------------------------------------------------------------------------------- 1 | 10 | 11 | 22 | 23 |
24 | {% with errors = get_flashed_messages(category_filter=["error"]) %} 25 | {% if errors %} 26 | 31 | {% endif %} 32 | {% endwith %} 33 |
34 | -------------------------------------------------------------------------------- /flask-multiple-files-upload/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | UPLOAD_FOLDER = 'D:/uploads' 4 | 5 | app = Flask(__name__) 6 | app.secret_key = "secret key" 7 | app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER 8 | app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 9 | -------------------------------------------------------------------------------- /flask-multiple-files-upload/main.py: -------------------------------------------------------------------------------- 1 | import os 2 | #import magic 3 | import urllib.request 4 | from app import app 5 | from flask import Flask, flash, request, redirect, render_template 6 | from werkzeug.utils import secure_filename 7 | 8 | ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) 9 | 10 | def allowed_file(filename): 11 | return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS 12 | 13 | @app.route('/') 14 | def upload_form(): 15 | return render_template('upload.html') 16 | 17 | @app.route('/', methods=['POST']) 18 | def upload_file(): 19 | if request.method == 'POST': 20 | # check if the post request has the files part 21 | if 'files[]' not in request.files: 22 | flash('No file part') 23 | return redirect(request.url) 24 | files = request.files.getlist('files[]') 25 | for file in files: 26 | if file and allowed_file(file.filename): 27 | filename = secure_filename(file.filename) 28 | file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) 29 | flash('File(s) successfully uploaded') 30 | return redirect('/') 31 | 32 | if __name__ == "__main__": 33 | app.run() 34 | -------------------------------------------------------------------------------- /flask-multiple-files-upload/readme.rst: -------------------------------------------------------------------------------- 1 | Please follow the tutorial https://roytuts.com/python-flask-multiple-files-upload-example/ 2 | -------------------------------------------------------------------------------- /flask-multiple-files-upload/templates/upload.html: -------------------------------------------------------------------------------- 1 | 2 | Python Flask Multiple Files Upload Example 3 |

Select file(s) to upload

4 |

5 | {% with messages = get_flashed_messages() %} 6 | {% if messages %} 7 |

12 | {% endif %} 13 | {% endwith %} 14 |

15 |
16 |
17 |

18 | 19 |

20 |
21 |

22 | 23 |

24 |
25 | -------------------------------------------------------------------------------- /flask-reload-changes-without-server-restart/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | config = { 4 | "DEBUG": True # run app in debug mode 5 | } 6 | 7 | app = Flask(__name__) 8 | 9 | # Flask to use the above defined config 10 | app.config.from_mapping(config) -------------------------------------------------------------------------------- /flask-reload-changes-without-server-restart/db.py: -------------------------------------------------------------------------------- 1 | from app import app 2 | from flaskext.mysql import MySQL 3 | 4 | mysql = MySQL() 5 | 6 | # MySQL configurations 7 | app.config['MYSQL_DATABASE_USER'] = 'root' 8 | app.config['MYSQL_DATABASE_PASSWORD'] = 'root' 9 | app.config['MYSQL_DATABASE_DB'] = 'roytuts' 10 | app.config['MYSQL_DATABASE_HOST'] = 'localhost' 11 | 12 | mysql.init_app(app) -------------------------------------------------------------------------------- /flask-reload-changes-without-server-restart/main.py: -------------------------------------------------------------------------------- 1 | import pymysql 2 | from app import app 3 | from db import mysql 4 | from flask import render_template 5 | 6 | @app.route('/') 7 | def users(): 8 | conn = None 9 | cursor = None 10 | try: 11 | conn = mysql.connect() 12 | cursor = conn.cursor(pymysql.cursors.DictCursor) 13 | cursor.execute("SELECT * FROM user") 14 | rows = cursor.fetchall() 15 | #print(rows) 16 | return render_template('index.html', rows=rows) 17 | except Exception as e: 18 | print(e) 19 | finally: 20 | if cursor: 21 | cursor.close() 22 | if conn: 23 | conn.close() 24 | 25 | if __name__ == "__main__": 26 | app.run() -------------------------------------------------------------------------------- /flask-reload-changes-without-server-restart/readme.rst: -------------------------------------------------------------------------------- 1 | You can read tutorial https://roytuts.com/reload-changes-in-flask-web-app-without-server-restart/ -------------------------------------------------------------------------------- /flask-reload-changes-without-server-restart/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | Python Flask - Reload Changes Without Server Restart 3 |

Reload Changes Without Server Restart in Flask

4 | 5 |
6 |

User Details

7 | {% for row in rows %} 8 |

Id: {{ row['id']|safe }}

9 |

Name: {{ row['name']|safe }}

10 |

Email: {{ row['email']|safe }}

11 |

Phone: {{ row['phone']|safe }}

12 |

Address: {{ row['address']|safe }}

13 | {% endfor %} 14 |

15 |

16 | -------------------------------------------------------------------------------- /flask-rest-mongodb/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from flask_pymongo import PyMongo 3 | 4 | app = Flask(__name__) 5 | app.secret_key = "secret key" 6 | app.config["MONGO_URI"] = "mongodb://localhost:27017/roytuts" 7 | mongo = PyMongo(app) 8 | -------------------------------------------------------------------------------- /flask-rest-mongodb/main.py: -------------------------------------------------------------------------------- 1 | from app import app, mongo 2 | from bson.json_util import dumps 3 | from bson.objectid import ObjectId 4 | from flask import jsonify, flash, request 5 | from werkzeug.security import generate_password_hash, check_password_hash 6 | 7 | @app.route('/add', methods=['POST']) 8 | def add_user(): 9 | _json = request.json 10 | _name = _json['name'] 11 | _email = _json['email'] 12 | _password = _json['pwd'] 13 | # validate the received values 14 | if _name and _email and _password and request.method == 'POST': 15 | #do not save password as a plain text 16 | _hashed_password = generate_password_hash(_password) 17 | # save details 18 | id = mongo.db.user.insert_one({'name': _name, 'email': _email, 'pwd': _hashed_password}) 19 | resp = jsonify('User added successfully!') 20 | resp.status_code = 200 21 | return resp 22 | else: 23 | return not_found() 24 | 25 | @app.route('/users') 26 | def users(): 27 | users = mongo.db.user.find() 28 | resp = dumps(users) 29 | return resp 30 | 31 | @app.route('/user/') 32 | def user(id): 33 | user = mongo.db.user.find_one({'_id': ObjectId(id)}) 34 | resp = dumps(user) 35 | return resp 36 | 37 | @app.route('/update', methods=['PUT']) 38 | def update_user(): 39 | _json = request.json 40 | _id = _json['_id'] 41 | _name = _json['name'] 42 | _email = _json['email'] 43 | _password = _json['pwd'] 44 | # validate the received values 45 | if _name and _email and _password and _id and request.method == 'PUT': 46 | #do not save password as a plain text 47 | _hashed_password = generate_password_hash(_password) 48 | # save edits 49 | mongo.db.user.update_one({'_id': ObjectId(_id['$oid']) if '$oid' in _id else ObjectId(_id)}, {'$set': {'name': _name, 'email': _email, 'pwd': _hashed_password}}) 50 | resp = jsonify('User updated successfully!') 51 | resp.status_code = 200 52 | return resp 53 | else: 54 | return not_found() 55 | 56 | @app.route('/delete/', methods=['DELETE']) 57 | def delete_user(id): 58 | mongo.db.user.delete_one({'_id': ObjectId(id)}) 59 | resp = jsonify('User deleted successfully!') 60 | resp.status_code = 200 61 | return resp 62 | 63 | @app.errorhandler(404) 64 | def not_found(error=None): 65 | message = { 66 | 'status': 404, 67 | 'message': 'Not Found: ' + request.url, 68 | } 69 | resp = jsonify(message) 70 | resp.status_code = 404 71 | 72 | return resp 73 | 74 | if __name__ == "__main__": 75 | app.run() 76 | -------------------------------------------------------------------------------- /flask-rest-mongodb/readme.rst: -------------------------------------------------------------------------------- 1 | Please follow the tutorial https://roytuts.com/flask-rest-api-mongodb-crud-example/ 2 | -------------------------------------------------------------------------------- /google-charts/pie-chart/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | app = Flask(__name__) 4 | -------------------------------------------------------------------------------- /google-charts/pie-chart/main.py: -------------------------------------------------------------------------------- 1 | from app import app 2 | from flask import jsonify, request, render_template 3 | 4 | @app.route('/google-charts/pie-chart') 5 | def google_pie_chart(): 6 | data = {'Task' : 'Hours per Day', 'Work' : 11, 'Eat' : 2, 'Commute' : 2, 'Watching TV' : 2, 'Sleeping' : 7} 7 | #print(data) 8 | return render_template('pie-chart.html', data=data) 9 | 10 | if __name__ == "__main__": 11 | app.run() 12 | -------------------------------------------------------------------------------- /google-charts/pie-chart/readme.rst: -------------------------------------------------------------------------------- 1 | Please follow the tutorial https://roytuts.com/google-pie-chart-using-python-flask/ 2 | -------------------------------------------------------------------------------- /google-charts/pie-chart/templates/pie-chart.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Show Data on Google Pie Chart using Python Flask 6 | 7 | 37 | 38 | 39 |
40 |

Google Pie Chart using Python Flask

41 | 42 |
43 |
44 | 45 | 46 | -------------------------------------------------------------------------------- /python-flask-ajax-file-upload/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | UPLOAD_FOLDER = 'C:/uploads' 4 | 5 | app = Flask(__name__) 6 | app.secret_key = "secret key" 7 | app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER 8 | app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 9 | -------------------------------------------------------------------------------- /python-flask-ajax-file-upload/main.py: -------------------------------------------------------------------------------- 1 | import os 2 | import urllib.request 3 | from app import app 4 | from flask import Flask, flash, request, redirect, render_template, jsonify 5 | from werkzeug.utils import secure_filename 6 | 7 | ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) 8 | 9 | def allowed_file(filename): 10 | return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS 11 | 12 | @app.route('/') 13 | def upload_form(): 14 | return render_template('file-upload.html') 15 | 16 | @app.route('/python-flask-files-upload', methods=['POST']) 17 | def upload_file(): 18 | # check if the post request has the file part 19 | if 'files[]' not in request.files: 20 | resp = jsonify({'message' : 'No file part in the request'}) 21 | resp.status_code = 400 22 | return resp 23 | 24 | files = request.files.getlist('files[]') 25 | 26 | errors = {} 27 | success = False 28 | 29 | for file in files: 30 | if file and allowed_file(file.filename): 31 | filename = secure_filename(file.filename) 32 | file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) 33 | success = True 34 | else: 35 | errors[file.filename] = 'File type is not allowed' 36 | 37 | if success and errors: 38 | errors['message'] = 'File(s) successfully uploaded' 39 | resp = jsonify(errors) 40 | resp.status_code = 206 41 | return resp 42 | if success: 43 | resp = jsonify({'message' : 'Files successfully uploaded'}) 44 | resp.status_code = 201 45 | return resp 46 | else: 47 | resp = jsonify(errors) 48 | resp.status_code = 400 49 | return resp 50 | 51 | if __name__ == "__main__": 52 | app.run() 53 | -------------------------------------------------------------------------------- /python-flask-ajax-file-upload/readme.rst: -------------------------------------------------------------------------------- 1 | Please follow the tutorial https://roytuts.com/ajax-files-upload-using-python-flask-jquery/ 2 | -------------------------------------------------------------------------------- /python-flask-ajax-file-upload/templates/file-upload.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Python Flask File(s) Upload Example 5 | 6 | 7 | 8 | 9 |

Python Flask File(s) Upload - Select file(s) to upload

10 |
11 |

12 |

13 | 14 | 15 |

16 |
17 | 57 | 58 | -------------------------------------------------------------------------------- /python-flask-ajax-mysql-login-logout/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | app = Flask(__name__) 4 | app.secret_key = "secret key" 5 | -------------------------------------------------------------------------------- /python-flask-ajax-mysql-login-logout/dao.py: -------------------------------------------------------------------------------- 1 | import pymysql 2 | from db_config import mysql 3 | #from werkzeug import check_password_hash version 1.x 4 | from werkzeug.security import check_password_hash # version 2.x, 3.x 5 | 6 | def login(email, pwd): 7 | conn = None; 8 | cursor = None; 9 | 10 | try: 11 | conn = mysql.connect() 12 | cursor = conn.cursor() 13 | 14 | sql = "SELECT email, pwd FROM user WHERE email=%s" 15 | sql_where = (email,) 16 | 17 | cursor.execute(sql, sql_where) 18 | row = cursor.fetchone() 19 | 20 | if row: 21 | if check_password_hash(row[1], pwd): 22 | return row[0] 23 | return None 24 | 25 | except Exception as e: 26 | print(e) 27 | 28 | finally: 29 | if cursor and conn: 30 | cursor.close() 31 | conn.close() 32 | -------------------------------------------------------------------------------- /python-flask-ajax-mysql-login-logout/db_config.py: -------------------------------------------------------------------------------- 1 | from app import app 2 | from flaskext.mysql import MySQL 3 | 4 | mysql = MySQL() 5 | 6 | # MySQL configurations 7 | app.config['MYSQL_DATABASE_USER'] = 'root' 8 | app.config['MYSQL_DATABASE_PASSWORD'] = 'root' 9 | app.config['MYSQL_DATABASE_DB'] = 'roytuts' 10 | app.config['MYSQL_DATABASE_HOST'] = 'localhost' 11 | mysql.init_app(app) 12 | -------------------------------------------------------------------------------- /python-flask-ajax-mysql-login-logout/main.py: -------------------------------------------------------------------------------- 1 | import rest 2 | from app import app 3 | from flask import render_template 4 | 5 | @app.route('/') 6 | def home_page(): 7 | return render_template('index.html') 8 | 9 | @app.route('/login/page') 10 | def login_page(): 11 | return render_template('login.html') 12 | 13 | if __name__ == "__main__": 14 | app.run() 15 | -------------------------------------------------------------------------------- /python-flask-ajax-mysql-login-logout/readme.rst: -------------------------------------------------------------------------------- 1 | Please follow the tutorial https://roytuts.com/jquery-ajax-based-login-logout-using-python-flask-mysql/ 2 | -------------------------------------------------------------------------------- /python-flask-ajax-mysql-login-logout/rest.py: -------------------------------------------------------------------------------- 1 | import dao 2 | from app import app 3 | from flask import jsonify, request, session 4 | 5 | @app.route('/login', methods=['POST']) 6 | def login(): 7 | _json = request.json 8 | #print(_json) 9 | _username = _json['username'] 10 | _password = _json['password'] 11 | 12 | if _username and _password: 13 | user = dao.login(_username, _password) 14 | 15 | if user != None: 16 | session['username'] = user 17 | return jsonify({'message' : 'User logged in successfully'}) 18 | 19 | resp = jsonify({'message' : 'Bad Request - invalid credendtials'}) 20 | resp.status_code = 400 21 | return resp 22 | 23 | @app.route('/logout') 24 | def logout(): 25 | if 'username' in session: 26 | session.pop('username', None) 27 | return jsonify({'message' : 'You successfully logged out'}) 28 | -------------------------------------------------------------------------------- /python-flask-ajax-mysql-login-logout/static/js/auth.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function() { 2 | var isLoggedIn = localStorage.getItem('loggedin'); 3 | 4 | if(isLoggedIn == 1) { 5 | $('#sign').hide(); 6 | $('#loginform').hide(); 7 | $('#signupform').hide(); 8 | $('#logoff').show(); 9 | } else { 10 | $('#sign').show(); 11 | $('#logoff').hide(); 12 | } 13 | 14 | $('#loginSubmit').on('click', function(e) { 15 | e.preventDefault(); 16 | 17 | var email = $('#email').val(); 18 | var pwd = $('#password').val(); 19 | 20 | var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/i; 21 | 22 | if(email != "" && pwd != "" ) { 23 | if(!regex.test(email)) { 24 | $('#msg').html('Invalid email address'); 25 | } else { 26 | $.ajax({ 27 | method: "POST", 28 | url: '/login', 29 | contentType: 'application/json;charset=UTF-8', 30 | data: JSON.stringify({'username': email, 'password': pwd}), 31 | dataType: "json", 32 | success: function(data) { 33 | localStorage.setItem('loggedin', 1); 34 | 35 | $('#sign').hide(); 36 | $('#loginform').hide(); 37 | $('#logoff').show(); 38 | $('#msg').html('You are logged in'); 39 | }, 40 | statusCode: { 41 | 400: function() { 42 | $('#msg').html('Bad request - invalid credentials'); 43 | } 44 | }, 45 | error: function(err) { 46 | console.log(err); 47 | } 48 | }); 49 | } 50 | } else { 51 | $('#msg').html('Invalid username and password'); 52 | } 53 | }); 54 | 55 | $('#logout').on('click', function(e) { 56 | e.preventDefault(); 57 | 58 | $.ajax({ 59 | url: '/logout', 60 | dataType: "json", 61 | success: function(data) { 62 | localStorage.setItem('loggedin', 0); 63 | $('#sign').show(); 64 | $('#logoff').hide(); 65 | $('#msg').html('You are logged off'); 66 | }, 67 | error: function(err) { 68 | console.log(err); 69 | } 70 | }); 71 | }); 72 | }); 73 | -------------------------------------------------------------------------------- /python-flask-ajax-mysql-login-logout/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | jQuery AJAX Login Logout using Python Flask MySQL 6 | 7 | 11 | 12 | 13 | 14 |
15 | 25 |
26 | 27 |
28 | 29 | This is a home page 30 | 31 |
32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /python-flask-ajax-mysql-login-logout/templates/login.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | jQuery AJAX Login Logout using Python Flask MySQL 6 | 7 | 11 | 12 | 13 | 14 |
15 | 25 |
26 | 27 |
28 | 29 |
30 |
31 |
32 |

Login

33 |
34 |

35 | 36 |

37 |

38 | 39 |

40 |
41 |

42 | 43 |

44 |
45 | 46 |
47 | 48 | 49 | 50 | -------------------------------------------------------------------------------- /python-flask-ajax-mysql-login-logout/user.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE `user` ( 2 | `id` int unsigned NOT NULL AUTO_INCREMENT, 3 | `name` varchar(50) NULL, 4 | `email` varchar(50) NULL, 5 | `pwd` varchar(255) NULL, 6 | `admin` tinyint DEFAULT 0, 7 | PRIMARY KEY (`id`) 8 | ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 9 | 10 | insert into `user`(`id`,`name`,`email`,`pwd`,`admin`) values 11 | (1,'S Roy','roy@email.com','pbkdf2:sha256:150000$k1Ud5dzh$d0347f416e89ea486b33c988c9be65730329b2dd6d712f73c9920103a006a82e',1); 12 | -------------------------------------------------------------------------------- /python-flask-ajax-mysql-registration/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | app = Flask(__name__) 4 | #app.secret_key = "secret key" -------------------------------------------------------------------------------- /python-flask-ajax-mysql-registration/dao.py: -------------------------------------------------------------------------------- 1 | import pymysql 2 | from db_config import mysql 3 | #from werkzeug import generate_password_hash, check_password_hash 4 | from werkzeug.security import generate_password_hash, check_password_hash 5 | 6 | def user_exist(email): 7 | conn = None; 8 | cursor = None; 9 | 10 | try: 11 | conn = mysql.connect() 12 | cursor = conn.cursor() 13 | 14 | sql = "SELECT email FROM user WHERE email=%s" 15 | sql_where = (email,) 16 | 17 | cursor.execute(sql, sql_where) 18 | row = cursor.fetchone() 19 | 20 | if row: 21 | return True 22 | return False 23 | 24 | except Exception as e: 25 | print(e) 26 | 27 | finally: 28 | if cursor and conn: 29 | cursor.close() 30 | conn.close() 31 | 32 | def register(email, name, pwd): 33 | conn = None; 34 | cursor = None; 35 | 36 | try: 37 | conn = mysql.connect() 38 | cursor = conn.cursor() 39 | 40 | sql = "INSERT INTO user(name, email, pwd) VALUES(%s, %s, %s)" 41 | data = (name, email, generate_password_hash(pwd),) 42 | 43 | cursor.execute(sql, data) 44 | 45 | conn.commit() 46 | 47 | except Exception as e: 48 | print(e) 49 | 50 | finally: 51 | if cursor and conn: 52 | cursor.close() 53 | conn.close() -------------------------------------------------------------------------------- /python-flask-ajax-mysql-registration/db_config.py: -------------------------------------------------------------------------------- 1 | from app import app 2 | from flaskext.mysql import MySQL 3 | 4 | mysql = MySQL() 5 | 6 | # MySQL configurations 7 | app.config['MYSQL_DATABASE_USER'] = 'root' 8 | app.config['MYSQL_DATABASE_PASSWORD'] = 'root' 9 | app.config['MYSQL_DATABASE_DB'] = 'roytuts' 10 | app.config['MYSQL_DATABASE_HOST'] = 'localhost' 11 | mysql.init_app(app) -------------------------------------------------------------------------------- /python-flask-ajax-mysql-registration/main.py: -------------------------------------------------------------------------------- 1 | import rest 2 | from app import app 3 | from flask import render_template 4 | 5 | @app.route('/') 6 | def home(): 7 | return render_template('signup.html') 8 | 9 | if __name__ == "__main__": 10 | app.run() -------------------------------------------------------------------------------- /python-flask-ajax-mysql-registration/readme.rst: -------------------------------------------------------------------------------- 1 | You can read tutorial https://roytuts.com/jquery-ajax-based-registration-system-using-python-flask-mysql/ -------------------------------------------------------------------------------- /python-flask-ajax-mysql-registration/rest.py: -------------------------------------------------------------------------------- 1 | import dao 2 | import json 3 | from app import app 4 | from flask import jsonify, request 5 | 6 | @app.route('/signup', methods=['POST']) 7 | def signup(): 8 | _json = request.json 9 | _name = _json['name'] 10 | _email = _json['email'] 11 | _pwd = _json['password'] 12 | 13 | if _email and _name and _pwd: 14 | 15 | user_exist = dao.user_exist(_email) 16 | 17 | if user_exist == True: 18 | resp = jsonify({'message' : 'User already registered'}) 19 | resp.status_code = 409 20 | return resp 21 | else: 22 | dao.register(_email, _name, _pwd) 23 | 24 | resp = jsonify({'message' : 'User registered successfully'}) 25 | resp.status_code = 201 26 | return resp 27 | else: 28 | resp = jsonify({'message' : 'Bad Request - invalid parameters'}) 29 | resp.status_code = 400 30 | return resp -------------------------------------------------------------------------------- /python-flask-ajax-mysql-registration/static/js/register.js: -------------------------------------------------------------------------------- 1 | $(document).ready(function() { 2 | $('#signupSubmit').on('click', function(e) { 3 | e.preventDefault(); 4 | 5 | var name = $('#fullname').val(); 6 | var email = $('#email').val(); 7 | var pwd = $('#password').val(); 8 | var cnfpwd = $('#cnfpassword').val(); 9 | 10 | var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/i; 11 | 12 | if(email != "" && pwd != "" && cnfpwd != "") { 13 | if(pwd != cnfpwd) { 14 | $('#msg').html('Password and confirm password must match'); 15 | } else if(!regex.test(email)) { 16 | $('#msg').html('Invalid email address'); 17 | } else { 18 | $.ajax({ 19 | method: "POST", 20 | url: '/signup', 21 | contentType: 'application/json;charset=UTF-8', 22 | data: JSON.stringify({'name': name, 'email': email, 'password': pwd}), 23 | dataType: "json", 24 | success: function(data) { 25 | $('#signupform').hide(); 26 | $('#msg').html('You are registered successfully'); 27 | },statusCode: { 28 | 400: function() { 29 | $('#msg').html('Bad request parameters'); 30 | }, 31 | 409 : function() { 32 | $('#msg').html('You are already registered user'); 33 | } 34 | }, 35 | error: function(err) { 36 | console.log(err); 37 | } 38 | }); 39 | } 40 | } else { 41 | $('#msg').html('All fields are required'); 42 | } 43 | }); 44 | }); -------------------------------------------------------------------------------- /python-flask-ajax-mysql-registration/templates/signup.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | jQuery AJAX based Registration System using Python Flask MySQL 6 | 7 | 11 | 12 | 13 |
14 |
15 |
16 |
17 |

Sign Up

18 |
19 |

20 | 21 |

22 |

23 | 24 |

25 |

26 | 27 |

28 |

29 | 30 |

31 |
32 |

33 | 34 |

35 |
36 |
37 | 38 | -------------------------------------------------------------------------------- /python-flask-autocomplete-input-suggestion/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | app = Flask(__name__) 4 | app.secret_key = "secret key" -------------------------------------------------------------------------------- /python-flask-autocomplete-input-suggestion/data/results.json: -------------------------------------------------------------------------------- 1 | [ 2 | "Lorem Ipsum is simply dummy text of the printing and typesetting", 3 | "Lorem Ipsum has been the industry's standard dummy", 4 | "nd scrambled it to make a type specimen book. It", 5 | "typesetting, remaining essentially unchanged. It ", 6 | "sum passages, and more recently with desktop publi", 7 | "Contrary to popular belief, Lorem Ipsum is not sim", 8 | "professor at Hampden-Sydney College in Virginia, looked up one", 9 | "passage, and going through the cites of the word in", 10 | "comes from sections 1.10.32 and 1.10.33 of \"de Finibus Bonorum", 11 | "BC. This book is a treatise on the theory of ethics, very popu", 12 | "here are many variations of passages of Lorem Ipsum availa", 13 | "believable. If you are going to use a passage of Lorem Ips", 14 | "middle of text. All the Lorem Ipsum generators on the Intern", 15 | "tend to repeat predefined chunks as necessary, making this the", 16 | "first true generator on the Internet. It uses a dictionary of over 20", 17 | "he standard chunk of Lorem Ipsum used since the 1500s i", 18 | "1.10.33 from \"de Finibus Bonorum et Malorum\" by Cicero are als", 19 | "reproduced in their exact original form, accompanied by English", 20 | "eadable content of a page when looking at its layout. The point" 21 | ] -------------------------------------------------------------------------------- /python-flask-autocomplete-input-suggestion/main.py: -------------------------------------------------------------------------------- 1 | import os, json 2 | from app import app 3 | from flask import Flask, jsonify, request, redirect, render_template 4 | 5 | @app.route('/') 6 | def upload_form(): 7 | return render_template('autocomplete.html') 8 | 9 | @app.route('/search', methods=['POST']) 10 | def search(): 11 | term = request.form['q'] 12 | print ('term: ', term) 13 | 14 | SITE_ROOT = os.path.realpath(os.path.dirname(__file__)) 15 | json_url = os.path.join(SITE_ROOT, "data", "results.json") 16 | json_data = json.loads(open(json_url).read()) 17 | #print (json_data) 18 | #print (json_data[0]) 19 | 20 | filtered_dict = [v for v in json_data if term in v] 21 | #print(filtered_dict) 22 | 23 | resp = jsonify(filtered_dict) 24 | resp.status_code = 200 25 | return resp 26 | 27 | if __name__ == "__main__": 28 | app.run() -------------------------------------------------------------------------------- /python-flask-autocomplete-input-suggestion/readme.rst: -------------------------------------------------------------------------------- 1 | You can go through the tutorial https://roytuts.com/autocomplete-input-suggestion-using-python-and-flask/ -------------------------------------------------------------------------------- /python-flask-autocomplete-input-suggestion/templates/autocomplete.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Autocomplete input suggestion using Python and Flask 5 | 6 | 7 | 8 | 9 | 10 | 36 | 37 | 38 |
39 |

Autocomplete input suggestion using Python and Flask

40 |

41 |    42 |

43 |
44 | -------------------------------------------------------------------------------- /python-flask-delete-multiple-rows-ajax-jquery-mysql/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | app = Flask(__name__) -------------------------------------------------------------------------------- /python-flask-delete-multiple-rows-ajax-jquery-mysql/dao.py: -------------------------------------------------------------------------------- 1 | import pymysql 2 | from db import mysql 3 | 4 | def products(): 5 | try: 6 | conn = mysql.connect() 7 | cursor = conn.cursor(pymysql.cursors.DictCursor) 8 | 9 | sql = "SELECT * FROM product" 10 | 11 | cursor.execute(sql) 12 | 13 | rows = cursor.fetchall() 14 | 15 | return rows 16 | 17 | except Exception as e: 18 | print(e) 19 | 20 | finally: 21 | if cursor and conn: 22 | cursor.close() 23 | conn.close() 24 | 25 | def delete_products(ids): 26 | try: 27 | conn = mysql.connect() 28 | cursor = conn.cursor(pymysql.cursors.DictCursor) 29 | 30 | sql = "DELETE FROM product WHERE id IN (" + ",".join(ids) + ")" 31 | 32 | cursor.execute(sql) 33 | 34 | conn.commit() 35 | 36 | return True 37 | 38 | except Exception as e: 39 | print(e) 40 | 41 | return False 42 | 43 | finally: 44 | if cursor and conn: 45 | cursor.close() 46 | conn.close() -------------------------------------------------------------------------------- /python-flask-delete-multiple-rows-ajax-jquery-mysql/db.py: -------------------------------------------------------------------------------- 1 | from app import app 2 | from flaskext.mysql import MySQL 3 | 4 | mysql = MySQL() 5 | 6 | # MySQL configurations 7 | app.config['MYSQL_DATABASE_USER'] = 'root' 8 | app.config['MYSQL_DATABASE_PASSWORD'] = 'root' 9 | app.config['MYSQL_DATABASE_DB'] = 'roytuts' 10 | app.config['MYSQL_DATABASE_HOST'] = 'localhost' 11 | mysql.init_app(app) -------------------------------------------------------------------------------- /python-flask-delete-multiple-rows-ajax-jquery-mysql/main.py: -------------------------------------------------------------------------------- 1 | import dao 2 | import pymysql 3 | from app import app 4 | from flask import jsonify, request, render_template 5 | 6 | @app.route('/delete_products', methods=['POST']) 7 | def delete_products(): 8 | ids = request.json['ids'] 9 | 10 | # validate the received values 11 | if ids: 12 | if ',' in ids: 13 | ids = ids.split(',') 14 | 15 | resp = dao.delete_products(ids) 16 | 17 | if resp: 18 | resp = jsonify('Products deleted successfully') 19 | resp.status_code = 200 20 | return resp 21 | else: 22 | resp = jsonify('Something went wrong during products deletion') 23 | resp.status_code = 500 24 | return resp 25 | else: 26 | resp = jsonify('Make sure you pass the required parameter') 27 | resp.status_code = 400 28 | return resp 29 | 30 | @app.route('/') 31 | def home(): 32 | products = dao.products() 33 | return render_template('app.html', products = products) 34 | 35 | if __name__ == "__main__": 36 | app.run() -------------------------------------------------------------------------------- /python-flask-delete-multiple-rows-ajax-jquery-mysql/product.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE `product` ( 2 | `id` int unsigned NOT NULL AUTO_INCREMENT, 3 | `name` varchar(255) NOT NULL, 4 | `code` varchar(255) NOT NULL, 5 | `price` double NOT NULL, 6 | PRIMARY KEY (`id`) 7 | ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4; 8 | 9 | INSERT INTO `product` (`id`, `name`, `code`, `price`) VALUES 10 | (1, 'American Tourist', 'AMTR01', 12000.00), 11 | (2, 'EXP Portable Hard Drive', 'USB02', 5000.00), 12 | (3, 'Shoes', 'SH03', 1000.00), 13 | (4, 'XP 1155 Intel Core Laptop', 'LPN4', 80000.00), 14 | (5, 'FinePix Pro2 3D Camera', '3DCAM01', 150000.00), 15 | (6, 'Simple Mobile', 'MB06', 3000.00), 16 | (7, 'Luxury Ultra thin Wrist Watch', 'WristWear03', 3000.00), 17 | (8, 'Headphone', 'HD08', 400.00); 18 | -------------------------------------------------------------------------------- /python-flask-delete-multiple-rows-ajax-jquery-mysql/readme.rst: -------------------------------------------------------------------------------- 1 | Please follow the tutorial https://roytuts.com/delete-multiple-rows-from-table-using-flask-ajax-jquery-mysql/ 2 | -------------------------------------------------------------------------------- /python-flask-delete-multiple-rows-ajax-jquery-mysql/static/css/table.css: -------------------------------------------------------------------------------- 1 | table.datatable { 2 | width:100%; 3 | border: none; 4 | background:#fff; 5 | } 6 | table.datatable td.table_foot { 7 | border: none; 8 | background: #fff; 9 | text-align: center; 10 | } 11 | table.datatable tr.odd_col { 12 | background: none; 13 | } 14 | table.datatable tr.even_col { 15 | background: #ddd; 16 | } 17 | table.datatable td { 18 | font-size:10pt; 19 | padding:5px 10px; 20 | border-bottom:1px solid #ddd; 21 | text-align: left; 22 | } 23 | table.datatable th { 24 | text-align: left; 25 | font-size: 8pt; 26 | padding: 10px 10px 7px; 27 | text-transform: uppercase; 28 | color: #fff; 29 | background-color: black; 30 | font-family: sans-serif; 31 | } -------------------------------------------------------------------------------- /python-flask-delete-multiple-rows-ajax-jquery-mysql/static/js/app.js: -------------------------------------------------------------------------------- 1 | $(function() { 2 | //If check_all checked then check all table rows 3 | $("#check_all").on("click", function () { 4 | if ($("input:checkbox").prop("checked")) { 5 | $("input:checkbox[name='row-check']").prop("checked", true); 6 | } else { 7 | $("input:checkbox[name='row-check']").prop("checked", false); 8 | } 9 | }); 10 | 11 | // Check each table row checkbox 12 | $("input:checkbox[name='row-check']").on("change", function () { 13 | var total_check_boxes = $("input:checkbox[name='row-check']").length; 14 | var total_checked_boxes = $("input:checkbox[name='row-check']:checked").length; 15 | 16 | // If all checked manually then check check_all checkbox 17 | if (total_check_boxes === total_checked_boxes) { 18 | $("#check_all").prop("checked", true); 19 | } 20 | else { 21 | $("#check_all").prop("checked", false); 22 | } 23 | }); 24 | 25 | $("#delete_selected").on("click", function () { 26 | var ids = ''; 27 | var comma = ''; 28 | $("input:checkbox[name='row-check']:checked").each(function() { 29 | ids = ids + comma + this.value; 30 | comma = ','; 31 | }); 32 | 33 | if(ids.length > 0) { 34 | $.ajax({ 35 | type: "POST", 36 | contentType: 'application/json;charset=UTF-8', 37 | url: "http://localhost:5000/delete_products", 38 | data: JSON.stringify({'ids': ids}), 39 | dataType: "json", 40 | cache: false, 41 | success: function(msg) { 42 | $("#msg").html(msg); 43 | }, 44 | error: function(jqXHR, textStatus, errorThrown) { 45 | $("#msg").html("" + textStatus + " " + errorThrown + ""); 46 | } 47 | }); 48 | } else { 49 | $("#msg").html('You must select at least one product for deletion'); 50 | } 51 | }); 52 | }); -------------------------------------------------------------------------------- /python-flask-delete-multiple-rows-ajax-jquery-mysql/templates/app.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Multiple Table Rows Deletion Example in Python, Flask, AJAX, jQuery, MySQL 6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 |

Multiple Table Rows Deletion Example in Python, Flask, AJAX, jQuery, MySQL

14 | 15 |
16 | {% if products %} 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | {% for p in products %} 31 | {% set row_class = ('even_col' if loop.index % 2 == 0 else 'odd_col') %} 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | {% endfor %} 40 | 41 |
IDCodeNamePrice
{{ p['id'] }}{{ p['code'] }}{{ p['name'] }}{{ p['price'] }}
42 | {% else %} 43 |

No Record Found

44 | {% endif %} 45 |
46 |
47 | 48 | 49 | -------------------------------------------------------------------------------- /python-flask-file-download/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | app = Flask(__name__) -------------------------------------------------------------------------------- /python-flask-file-download/html2pdf.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roytuts/flask/b5efbaf7d72c59765f0f29c18d9a83fde78e5d12/python-flask-file-download/html2pdf.pdf -------------------------------------------------------------------------------- /python-flask-file-download/info.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roytuts/flask/b5efbaf7d72c59765f0f29c18d9a83fde78e5d12/python-flask-file-download/info.xlsx -------------------------------------------------------------------------------- /python-flask-file-download/main.py: -------------------------------------------------------------------------------- 1 | from app import app 2 | from flask import Flask, send_file, render_template 3 | 4 | @app.route('/') 5 | def upload_form(): 6 | return render_template('download.html') 7 | 8 | @app.route('/download') 9 | def download_file(): 10 | #path = "html2pdf.pdf" 11 | #path = "info.xlsx" 12 | path = "simple.docx" 13 | #path = "sample.txt" 14 | return send_file(path, as_attachment=True) 15 | 16 | if __name__ == "__main__": 17 | app.run() -------------------------------------------------------------------------------- /python-flask-file-download/readme.rst: -------------------------------------------------------------------------------- 1 | Please follow the tutorial https://roytuts.com/how-to-download-file-using-python-flask/ 2 | -------------------------------------------------------------------------------- /python-flask-file-download/sample.txt: -------------------------------------------------------------------------------- 1 | I would love to try or hear the sample audio your app can produce. I do not want to purchase, because I've purchased so many apps that say they do something and do not deliver. 2 | 3 | Can you please add audio samples with text you've converted? I'd love to see the end results. 4 | 5 | Thanks! -------------------------------------------------------------------------------- /python-flask-file-download/simple.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roytuts/flask/b5efbaf7d72c59765f0f29c18d9a83fde78e5d12/python-flask-file-download/simple.docx -------------------------------------------------------------------------------- /python-flask-file-download/templates/download.html: -------------------------------------------------------------------------------- 1 | 2 | Python Flask File Download Example 3 |

Download a file

4 | 5 |

6 | Download 7 |

-------------------------------------------------------------------------------- /python-flask-login-logout/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | app = Flask(__name__) 4 | app.secret_key = "secret key" -------------------------------------------------------------------------------- /python-flask-login-logout/db_config.py: -------------------------------------------------------------------------------- 1 | from app import app 2 | from flaskext.mysql import MySQL 3 | 4 | mysql = MySQL() 5 | 6 | # MySQL configurations 7 | app.config['MYSQL_DATABASE_USER'] = 'root' 8 | app.config['MYSQL_DATABASE_PASSWORD'] = 'root' 9 | app.config['MYSQL_DATABASE_DB'] = 'roytuts' 10 | app.config['MYSQL_DATABASE_HOST'] = 'localhost' 11 | mysql.init_app(app) -------------------------------------------------------------------------------- /python-flask-login-logout/main.py: -------------------------------------------------------------------------------- 1 | import pymysql 2 | from app import app 3 | from db_config import mysql 4 | from flask import flash, session, render_template, request, redirect 5 | from werkzeug import generate_password_hash, check_password_hash 6 | 7 | @app.route('/') 8 | def index(): 9 | if 'email' in session: 10 | username = session['email'] 11 | return 'Logged in as ' + username + '
' + "click here to logout" 12 | return "You are not logged in
" + "click here to login" 13 | 14 | @app.route('/login') 15 | def login(): 16 | return render_template('login.html') 17 | 18 | @app.route('/submit', methods=['POST']) 19 | def login_submit(): 20 | _email = request.form['inputEmail'] 21 | _password = request.form['inputPassword'] 22 | # validate the received values 23 | if _email and _password and request.method == 'POST': 24 | #check user exists 25 | conn = mysql.connect() 26 | cursor = conn.cursor() 27 | sql = "SELECT * FROM tbl_user WHERE user_email=%s" 28 | sql_where = (_email,) 29 | cursor.execute(sql, sql_where) 30 | row = cursor.fetchone() 31 | if row: 32 | if check_password_hash(row[3], _password): 33 | session['email'] = row[1] 34 | cursor.close() 35 | conn.close() 36 | return redirect('/') 37 | else: 38 | flash('Invalid password!') 39 | return redirect('/login') 40 | else: 41 | flash('Invalid email/password!') 42 | return redirect('/login') 43 | 44 | @app.route('/logout') 45 | def logout(): 46 | session.pop('email', None) 47 | return redirect('/') 48 | 49 | if __name__ == "__main__": 50 | app.run() -------------------------------------------------------------------------------- /python-flask-login-logout/readme.rst: -------------------------------------------------------------------------------- 1 | You can read tutorial https://roytuts.com/python-login-and-logout-example/ -------------------------------------------------------------------------------- /python-flask-login-logout/templates/login.html: -------------------------------------------------------------------------------- 1 | 2 | User Login - Python Flask 3 |

Login

4 |

5 | {% with messages = get_flashed_messages() %} 6 | {% if messages %} 7 |

    8 | {% for message in messages %} 9 |
  • {{ message }}
  • 10 | {% endfor %} 11 |
12 | {% endif %} 13 | {% endwith %} 14 |

15 |
16 |
17 |

18 | 19 |

20 |

21 | 22 |

23 |
24 |

25 | 26 |

27 |
-------------------------------------------------------------------------------- /python-flask-mysql-ajax-username-availability-check/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | app = Flask(__name__) 4 | -------------------------------------------------------------------------------- /python-flask-mysql-ajax-username-availability-check/db_config.py: -------------------------------------------------------------------------------- 1 | from app import app 2 | from flaskext.mysql import MySQL 3 | 4 | mysql = MySQL() 5 | 6 | # MySQL configurations 7 | app.config['MYSQL_DATABASE_USER'] = 'root' 8 | app.config['MYSQL_DATABASE_PASSWORD'] = 'root' 9 | app.config['MYSQL_DATABASE_DB'] = 'roytuts' 10 | app.config['MYSQL_DATABASE_HOST'] = 'localhost' 11 | mysql.init_app(app) 12 | -------------------------------------------------------------------------------- /python-flask-mysql-ajax-username-availability-check/main.py: -------------------------------------------------------------------------------- 1 | import pymysql 2 | from app import app 3 | from db_config import mysql 4 | from flask import jsonify, request, render_template 5 | 6 | @app.route('/user_check', methods=['POST']) 7 | def username_check(): 8 | conn = None 9 | cursor = None 10 | try: 11 | username = request.form['username'] 12 | 13 | # validate the received values 14 | if username and request.method == 'POST': 15 | conn = mysql.connect() 16 | cursor = conn.cursor(pymysql.cursors.DictCursor) 17 | cursor.execute("SELECT * FROM user WHERE login_username=%s", username) 18 | row = cursor.fetchone() 19 | 20 | if row: 21 | resp = jsonify('Username unavailable') 22 | resp.status_code = 200 23 | return resp 24 | else: 25 | resp = jsonify('Username available') 26 | resp.status_code = 200 27 | return resp 28 | else: 29 | resp = jsonify('Username is required field.') 30 | resp.status_code = 200 31 | return resp 32 | except Exception as e: 33 | print(e) 34 | finally: 35 | cursor.close() 36 | conn.close() 37 | 38 | @app.route('/') 39 | def home(): 40 | return render_template('username.html') 41 | 42 | if __name__ == "__main__": 43 | app.run() 44 | -------------------------------------------------------------------------------- /python-flask-mysql-ajax-username-availability-check/readme.rst: -------------------------------------------------------------------------------- 1 | Please follow the tutorial https://roytuts.com/python-flask-username-availability-check-with-mysql-ajax/ 2 | -------------------------------------------------------------------------------- /python-flask-mysql-ajax-username-availability-check/templates/username.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Check username availability using Python Flask, AJAX, MySQL 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 |

Python Flask, AJAX, MySQL - username availability check

15 | 16 |
17 |
18 | Check username 19 |
20 |
21 | 22 |
23 |
24 |
25 |
26 |
27 | 28 | 29 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /python-flask-mysql-ajax-username-availability-check/user.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE `user` ( 2 | `user_id` int unsigned NOT NULL AUTO_INCREMENT, 3 | `login_username` varchar(100) NOT NULL, 4 | `login_password` varchar(255) NOT NULL, 5 | `last_login` timestamp NULL DEFAULT CURRENT_TIMESTAMP, 6 | PRIMARY KEY (`user_id`), 7 | UNIQUE KEY `login_email_UNIQUE` (`login_username`) 8 | ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=UTF8MB4; 9 | 10 | 11 | insert into `user`(`user_id`,`login_username`,`login_password`,`last_login`) 12 | values (1,'user1','$2a$08$S5IfrpOVOvFbbOSOmZpjsO5N9PXgEerTloK','2023-01-19 19:18:30'),(2,'user2','$2a$08$v1kJflweCK3FOcoAsmYAUCMxFa5Shh7c2','2023-02-10 19:22:46'); 13 | -------------------------------------------------------------------------------- /python-flask-mysql-crud/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | app = Flask(__name__) 4 | app.secret_key = "secret key" -------------------------------------------------------------------------------- /python-flask-mysql-crud/db_config.py: -------------------------------------------------------------------------------- 1 | from app import app 2 | from flaskext.mysql import MySQL 3 | 4 | mysql = MySQL() 5 | 6 | # MySQL configurations 7 | app.config['MYSQL_DATABASE_USER'] = 'root' 8 | app.config['MYSQL_DATABASE_PASSWORD'] = 'root' 9 | app.config['MYSQL_DATABASE_DB'] = 'roytuts' 10 | app.config['MYSQL_DATABASE_HOST'] = 'localhost' 11 | mysql.init_app(app) -------------------------------------------------------------------------------- /python-flask-mysql-crud/main.py: -------------------------------------------------------------------------------- 1 | import pymysql 2 | from app import app 3 | from tables import Results 4 | from db_config import mysql 5 | from flask import flash, render_template, request, redirect 6 | from werkzeug.security import generate_password_hash, check_password_hash 7 | 8 | @app.route('/new_user') 9 | def add_user_view(): 10 | return render_template('add.html') 11 | 12 | @app.route('/add', methods=['POST']) 13 | def add_user(): 14 | conn = None 15 | cursor = None 16 | try: 17 | _name = request.form['inputName'] 18 | _email = request.form['inputEmail'] 19 | _password = request.form['inputPassword'] 20 | # validate the received values 21 | if _name and _email and _password and request.method == 'POST': 22 | #do not save password as a plain text 23 | _hashed_password = generate_password_hash(_password) 24 | # save edits 25 | sql = "INSERT INTO tbl_user(user_name, user_email, user_password) VALUES(%s, %s, %s)" 26 | data = (_name, _email, _hashed_password,) 27 | conn = mysql.connect() 28 | cursor = conn.cursor() 29 | cursor.execute(sql, data) 30 | conn.commit() 31 | flash('User added successfully!') 32 | return redirect('/') 33 | else: 34 | return 'Error while adding user' 35 | except Exception as e: 36 | print(e) 37 | finally: 38 | cursor.close() 39 | conn.close() 40 | 41 | @app.route('/') 42 | def users(): 43 | conn = None 44 | cursor = None 45 | try: 46 | conn = mysql.connect() 47 | cursor = conn.cursor(pymysql.cursors.DictCursor) 48 | cursor.execute("SELECT * FROM tbl_user") 49 | rows = cursor.fetchall() 50 | table = Results(rows) 51 | table.border = True 52 | return render_template('users.html', table=table) 53 | except Exception as e: 54 | print(e) 55 | finally: 56 | cursor.close() 57 | conn.close() 58 | 59 | @app.route('/edit/') 60 | def edit_view(id): 61 | conn = None 62 | cursor = None 63 | try: 64 | conn = mysql.connect() 65 | cursor = conn.cursor(pymysql.cursors.DictCursor) 66 | cursor.execute("SELECT * FROM tbl_user WHERE user_id=%s", id) 67 | row = cursor.fetchone() 68 | if row: 69 | return render_template('edit.html', row=row) 70 | else: 71 | return 'Error loading #{id}'.format(id=id) 72 | except Exception as e: 73 | print(e) 74 | finally: 75 | cursor.close() 76 | conn.close() 77 | 78 | @app.route('/update', methods=['POST']) 79 | def update_user(): 80 | conn = None 81 | cursor = None 82 | try: 83 | _name = request.form['inputName'] 84 | _email = request.form['inputEmail'] 85 | _password = request.form['inputPassword'] 86 | _id = request.form['id'] 87 | # validate the received values 88 | if _name and _email and _password and _id and request.method == 'POST': 89 | #do not save password as a plain text 90 | _hashed_password = generate_password_hash(_password) 91 | print(_hashed_password) 92 | # save edits 93 | sql = "UPDATE tbl_user SET user_name=%s, user_email=%s, user_password=%s WHERE user_id=%s" 94 | data = (_name, _email, _hashed_password, _id,) 95 | conn = mysql.connect() 96 | cursor = conn.cursor() 97 | cursor.execute(sql, data) 98 | conn.commit() 99 | flash('User updated successfully!') 100 | return redirect('/') 101 | else: 102 | return 'Error while updating user' 103 | except Exception as e: 104 | print(e) 105 | finally: 106 | cursor.close() 107 | conn.close() 108 | 109 | @app.route('/delete/') 110 | def delete_user(id): 111 | conn = None 112 | cursor = None 113 | try: 114 | conn = mysql.connect() 115 | cursor = conn.cursor() 116 | cursor.execute("DELETE FROM tbl_user WHERE user_id=%s", (id,)) 117 | conn.commit() 118 | flash('User deleted successfully!') 119 | return redirect('/') 120 | except Exception as e: 121 | print(e) 122 | finally: 123 | cursor.close() 124 | conn.close() 125 | 126 | if __name__ == "__main__": 127 | app.run() -------------------------------------------------------------------------------- /python-flask-mysql-crud/readme.rst: -------------------------------------------------------------------------------- 1 | Please follow the tutorial https://roytuts.com/python-web-application-crud-example-using-flask-and-mysql/ 2 | -------------------------------------------------------------------------------- /python-flask-mysql-crud/tables.py: -------------------------------------------------------------------------------- 1 | from flask_table import Table, Col, LinkCol 2 | 3 | class Results(Table): 4 | user_id = Col('Id', show=False) 5 | user_name = Col('Name') 6 | user_email = Col('Email') 7 | user_password = Col('Password', show=False) 8 | edit = LinkCol('Edit', 'edit_view', url_kwargs=dict(id='user_id')) 9 | delete = LinkCol('Delete', 'delete_user', url_kwargs=dict(id='user_id')) -------------------------------------------------------------------------------- /python-flask-mysql-crud/templates/add.html: -------------------------------------------------------------------------------- 1 | 2 | Add User - Python Flask MySQL CRUD 3 |

Add User

4 |
5 |
6 |

7 | 8 |

9 |

10 | 11 |

12 |

13 | 14 |

15 |
16 |

17 | 18 |

19 |
-------------------------------------------------------------------------------- /python-flask-mysql-crud/templates/edit.html: -------------------------------------------------------------------------------- 1 | 2 | Edit User - Python Flask MySQL CRUD 3 |

Edit User

4 |
5 |
6 |

7 | 8 |

9 |

10 | 11 |

12 |

13 | 14 |

15 |
16 |

17 | 18 | 19 |

20 |
-------------------------------------------------------------------------------- /python-flask-mysql-crud/templates/users.html: -------------------------------------------------------------------------------- 1 | 2 | List of users - Python Flask MySQL CRUD 3 | 4 |

Add User

5 | 6 |

7 | {% with messages = get_flashed_messages() %} 8 | {% if messages %} 9 |

    10 | {% for message in messages %} 11 |
  • {{ message }}
  • 12 | {% endfor %} 13 |
14 | {% endif %} 15 | {% endwith %} 16 |

17 | 18 | {{ table }} -------------------------------------------------------------------------------- /python-flask-mysql-crud/user.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE `tbl_user` ( 2 | `user_id` bigint NOT NULL AUTO_INCREMENT, 3 | `user_name` varchar(45) DEFAULT NULL, 4 | `user_email` varchar(45) DEFAULT NULL, 5 | `user_password` varchar(255) DEFAULT NULL, 6 | PRIMARY KEY (`user_id`) 7 | ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 8 | -------------------------------------------------------------------------------- /python-flask-mysql-jquery-ajax-multi-step-registration/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | app = Flask(__name__) 4 | app.secret_key = "secret key" 5 | -------------------------------------------------------------------------------- /python-flask-mysql-jquery-ajax-multi-step-registration/db_config.py: -------------------------------------------------------------------------------- 1 | from app import app 2 | from flaskext.mysql import MySQL 3 | 4 | mysql = MySQL() 5 | 6 | # MySQL configurations 7 | app.config['MYSQL_DATABASE_USER'] = 'root' 8 | app.config['MYSQL_DATABASE_PASSWORD'] = 'root' 9 | app.config['MYSQL_DATABASE_DB'] = 'roytuts' 10 | app.config['MYSQL_DATABASE_HOST'] = 'localhost' 11 | mysql.init_app(app) 12 | -------------------------------------------------------------------------------- /python-flask-mysql-jquery-ajax-multi-step-registration/main.py: -------------------------------------------------------------------------------- 1 | import pymysql 2 | from app import app 3 | from db_config import mysql 4 | from flask import flash, render_template, request, redirect, url_for 5 | #from werkzeug import generate_password_hash, check_password_hash version 1.x 6 | from werkzeug.security import generate_password_hash, check_password_hash # version 2.x 7 | 8 | @app.route('/register', methods=['POST']) 9 | def save_user_info(): 10 | cursor = None 11 | try: 12 | name = request.form['name'] 13 | dob = request.form['dob'] 14 | gender = request.form['gender'] 15 | password = request.form['password'] 16 | phone = request.form['phone'] 17 | email = request.form['email'] 18 | address = request.form['address'] 19 | 20 | # validate the received values 21 | if name and dob and gender and password and phone and email and address and request.method == 'POST': 22 | 23 | #do not save password as a plain text 24 | _hashed_password = generate_password_hash(password) 25 | 26 | # save user information 27 | sql = "INSERT INTO user(name, password, email, phone, gender, dob, address) VALUES(%s, %s, %s, %s, %s, %s, %s)" 28 | data = (name, _hashed_password, email, phone, gender, dob, address) 29 | conn = mysql.connect() 30 | cursor = conn.cursor() 31 | cursor.execute(sql, data) 32 | conn.commit() 33 | 34 | flash('You registered successfully!') 35 | 36 | return redirect(url_for('.home')) 37 | else: 38 | return 'Error while saving user information' 39 | except Exception as e: 40 | print(e) 41 | finally: 42 | cursor.close() 43 | conn.close() 44 | 45 | @app.route('/') 46 | def home(): 47 | return render_template('multi-step-registration.html') 48 | 49 | if __name__ == "__main__": 50 | app.run() 51 | -------------------------------------------------------------------------------- /python-flask-mysql-jquery-ajax-multi-step-registration/readme.rst: -------------------------------------------------------------------------------- 1 | Please follow the tutorial https://roytuts.com/python-flask-multi-step-registration-form-with-mysql-jquery/ 2 | -------------------------------------------------------------------------------- /python-flask-mysql-jquery-ajax-multi-step-registration/templates/multi-step-registration.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Multi Step Registration 4 | 76 | 77 | 78 | 79 | 80 | 193 | 194 | 195 | 196 |
    197 |
  • Personal Detail
  • 198 |
  • Password
  • 199 |
  • Contact
  • 200 |
201 | 202 |
203 | {% with messages = get_flashed_messages() %} 204 | {% if messages %} 205 |
    206 | {% for message in messages %} 207 |
  • {{ message }}
  • 208 | {% endfor %} 209 |
210 | {% endif %} 211 | {% endwith %} 212 |
213 | 214 |
215 |
216 |
217 | 218 |
219 | 220 |
221 | 222 |
223 | 227 |
228 |
229 | 230 | 236 | 237 | 245 | 246 |
247 | 248 | 249 | 250 |
251 |
252 |
253 | 254 | 255 | -------------------------------------------------------------------------------- /python-flask-mysql-jquery-ajax-multi-step-registration/user.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE `user` ( 2 | `id` INT NOT NULL AUTO_INCREMENT, 3 | `name` VARCHAR(100) NOT NULL, 4 | `password` VARCHAR(255) NULL, 5 | `email` VARCHAR(100) NULL, 6 | `phone` VARCHAR(20) NOT NULL, 7 | `gender` VARCHAR(6) NOT NULL, 8 | `dob` VARCHAR(10) NOT NULL, 9 | `address` VARCHAR(255) NOT NULL, 10 | PRIMARY KEY (`id`) 11 | ) COLLATE='utf8mb4_unicode_ci' ENGINE=InnoDB; 12 | -------------------------------------------------------------------------------- /python-flask-mysql-jquery-ajax-star-rating-system/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | app = Flask(__name__) 4 | app.secret_key = "secret key" -------------------------------------------------------------------------------- /python-flask-mysql-jquery-ajax-star-rating-system/dao.py: -------------------------------------------------------------------------------- 1 | import pymysql 2 | from flask import request 3 | from db_config import mysql 4 | 5 | def get_blog_rating(blog_id): 6 | conn = None 7 | cursor = None 8 | 9 | try: 10 | conn = mysql.connect() 11 | cursor = conn.cursor(pymysql.cursors.DictCursor) 12 | 13 | sql = "SELECT COUNT(DISTINCT(vote_id)) total_rows, IFNULL(SUM(blog_vote),0) total_rating FROM blog_vote WHERE blog_id=%s LIMIT 1" 14 | sql_where = (blog_id,) 15 | 16 | cursor.execute(sql, sql_where) 17 | 18 | row = cursor.fetchone() 19 | 20 | return row 21 | except Exception as e: 22 | print(e) 23 | finally: 24 | cursor.close() 25 | conn.close() 26 | 27 | def get_blog_rating_from_ip(blog_id): 28 | conn = None 29 | cursor = None 30 | 31 | try: 32 | conn = mysql.connect() 33 | cursor = conn.cursor(pymysql.cursors.DictCursor) 34 | 35 | ip = request.remote_addr 36 | 37 | sql = "SELECT vote_id as vote_id FROM blog_vote WHERE ip_address=%s AND blog_id=%s LIMIT 1" 38 | sql_where = (ip, blog_id,) 39 | 40 | cursor.execute(sql, sql_where) 41 | 42 | row = cursor.fetchone() 43 | 44 | if row: 45 | vote_id = row['vote_id'] 46 | 47 | sql = "SELECT IFNULL(SUM(blog_vote),0) total_rating FROM blog_vote WHERE blog_id=%s LIMIT 1" 48 | sql_where = (blog_id,) 49 | 50 | cursor.execute(sql, sql_where) 51 | 52 | row = cursor.fetchone() 53 | 54 | rating = row['total_rating'] 55 | rating = rating 56 | 57 | return int(round(rating, 0)) 58 | else: 59 | return 0 60 | except Exception as e: 61 | print(e) 62 | finally: 63 | cursor.close() 64 | conn.close() 65 | 66 | def rate_blog(blog_id, rate): 67 | conn = None 68 | cursor = None 69 | 70 | try: 71 | conn = mysql.connect() 72 | cursor = conn.cursor(pymysql.cursors.DictCursor) 73 | 74 | ip = request.remote_addr 75 | 76 | sql = "SELECT vote_id FROM blog_vote WHERE ip_address=%s AND blog_id=%s LIMIT 1" 77 | sql_where = (ip, blog_id,) 78 | 79 | cursor.execute(sql, sql_where) 80 | 81 | row = cursor.fetchone() 82 | 83 | if row: 84 | vote_id = row['vote_id'] 85 | 86 | sql = "SELECT IFNULL(SUM(blog_vote),0) total_rating FROM blog_vote WHERE vote_id=%s AND blog_id=%s LIMIT 1" 87 | sql_where = (vote_id, blog_id,) 88 | 89 | cursor.execute(sql, sql_where) 90 | 91 | row = cursor.fetchone() 92 | 93 | rating = row['total_rating'] 94 | rating = rating 95 | 96 | return int(round(rating, 0)) 97 | else: 98 | sql = "INSERT INTO blog_vote(blog_vote, blog_id, ip_address) VALUES(%s, %s, %s)" 99 | sql_where = (rate, blog_id, ip,) 100 | 101 | cursor.execute(sql, sql_where) 102 | 103 | conn.commit() 104 | 105 | sql = "SELECT IFNULL(SUM(blog_vote),0) total_rating FROM blog_vote WHERE blog_id=%s LIMIT 1" 106 | sql_where = (blog_id,) 107 | 108 | cursor.execute(sql, sql_where) 109 | 110 | row = cursor.fetchone() 111 | 112 | rating = row['total_rating'] 113 | rating = rating 114 | 115 | return int(round(rating, 0)) 116 | 117 | except Exception as e: 118 | print(e) 119 | finally: 120 | cursor.close() 121 | conn.close() -------------------------------------------------------------------------------- /python-flask-mysql-jquery-ajax-star-rating-system/db_config.py: -------------------------------------------------------------------------------- 1 | from app import app 2 | from flaskext.mysql import MySQL 3 | 4 | mysql = MySQL() 5 | 6 | # MySQL configurations 7 | app.config['MYSQL_DATABASE_USER'] = 'root' 8 | app.config['MYSQL_DATABASE_PASSWORD'] = 'root' 9 | app.config['MYSQL_DATABASE_DB'] = 'roytuts' 10 | app.config['MYSQL_DATABASE_HOST'] = 'localhost' 11 | mysql.init_app(app) -------------------------------------------------------------------------------- /python-flask-mysql-jquery-ajax-star-rating-system/main.py: -------------------------------------------------------------------------------- 1 | import dao 2 | #import pymysql 3 | from app import app 4 | from db_config import mysql 5 | from flask import flash, render_template, request, redirect, url_for, jsonify 6 | 7 | @app.route('/rate', methods=['POST']) 8 | def rate_blog(): 9 | blog_id = request.json['blog_id'] 10 | rate = request.json['rate'] 11 | # validate the received values 12 | if blog_id and rate: 13 | curr_rate = dao.rate_blog(blog_id, rate) 14 | 15 | result = dao.get_blog_rating(blog_id) 16 | vote_rows = int(result['total_rows']) 17 | rating = result['total_rating'] 18 | vote_rate = int(round(rating/(vote_rows if vote_rows > 0 else 1), 0)) 19 | vote_dec_rate = int(round(vote_rate, 0)) 20 | 21 | curr_rating = int(round(curr_rate, 0)) 22 | 23 | return jsonify({'vote_rows' : vote_rows, 'vote_rate' : vote_rate, 'vote_dec_rate' : vote_dec_rate, 'vote_curr_rate' : curr_rating}) 24 | else: 25 | resp = jsonify({'message' : 'Bad Request - invalid credendtials'}) 26 | resp.status_code = 400 27 | return resp 28 | 29 | @app.route('/') 30 | def home(): 31 | #the hard-coded blog id value 1 should come from UI 32 | blog_id = 1; 33 | 34 | result = dao.get_blog_rating(blog_id) 35 | 36 | vote_rows = int(result['total_rows']) 37 | rating = result['total_rating'] 38 | vote_rate = int(round(rating/(vote_rows if vote_rows > 0 else 1), 0)) 39 | vote_dec_rate = int(round(vote_rate, 0)) 40 | 41 | vote_ip_rate = dao.get_blog_rating_from_ip(blog_id) 42 | 43 | return render_template('star-rate-vote.html', overall_rows=vote_rows, overall_rate=vote_rate, overall_dec_rate=vote_dec_rate, ip_rate=vote_ip_rate) 44 | 45 | if __name__ == "__main__": 46 | app.run() -------------------------------------------------------------------------------- /python-flask-mysql-jquery-ajax-star-rating-system/readme.rst: -------------------------------------------------------------------------------- 1 | Please follow the tutorial https://roytuts.com/jquery-ajax-based-voting-rating-system-using-flask-and-mysql 2 | -------------------------------------------------------------------------------- /python-flask-mysql-jquery-ajax-star-rating-system/static/css/blog_rating.css: -------------------------------------------------------------------------------- 1 | /*HOLD THE RATING AND THE BASE TOGETHER*/ 2 | .r { 3 | position: relative; 4 | } /*MUST BE ABSOLUTE TO STACKED*/ 5 | .rating, .transparent { 6 | position: absolute; 7 | } 8 | .rating { 9 | z-index: 1; 10 | } 11 | .star { 12 | background: url("../img/star.png"); 13 | cursor: pointer; float: left !important; /*KEEPS THE STAR NEXT TO EACH OTHER*/ 14 | height: 20px; width: 20px; 15 | } 16 | .transparent .star { 17 | opacity: .25; /*BASE STARS ARE TRANSPARENT UNTIL MOUSEOVER*/ 18 | } 19 | .rating .star { 20 | opacity: 1.0; /*CURRENT RATING IS VISIBLE UNTIL MOUSEOVER*/ 21 | } 22 | .votes { 23 | float: left; /*KEEPS THE NUMBER OF VOTES NEXT TO THE RATING & BASE*/ 24 | } -------------------------------------------------------------------------------- /python-flask-mysql-jquery-ajax-star-rating-system/static/img/star.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roytuts/flask/b5efbaf7d72c59765f0f29c18d9a83fde78e5d12/python-flask-mysql-jquery-ajax-star-rating-system/static/img/star.png -------------------------------------------------------------------------------- /python-flask-mysql-jquery-ajax-star-rating-system/static/js/blog_rating.js: -------------------------------------------------------------------------------- 1 | $(function () { 2 | $(".star").on("mouseover", function () { //SELECTING A STAR 3 | $(".rating").hide(); //HIDES THE CURRENT RATING WHEN MOUSE IS OVER A STAR 4 | var d = $(this).attr("id"); //GETS THE NUMBER OF THE STAR 5 | 6 | //HIGHLIGHTS EVERY STAR BEHIND IT 7 | for (i = (d - 1); i >= 0; i--) { 8 | $(".transparent .star:eq(" + i + ")").css({"opacity": "1.0"}); 9 | } 10 | }).on("click", function () { //RATING PROCESS 11 | var blog_id = $("#blog_content_id").val(); //GETS THE ID OF THE CONTENT 12 | var rate = $(this).attr("id"); //GETS THE NUMBER OF THE STAR 13 | 14 | $.ajax({ 15 | method: "POST", 16 | contentType: 'application/json;charset=UTF-8', 17 | data: JSON.stringify({'blog_id': blog_id, 'rate': rate}), 18 | url: "/rate", //CALLBACK 19 | success: function (e) { 20 | var stars = ''; 21 | 22 | for(var i=1;i<=e.vote_rate;i++){ 23 | stars += '
'; 24 | } 25 | 26 | var str = '
' + stars + '
(' + e.vote_dec_rate + '/5, ' + e.vote_rows + ' ' + (e.vote_rows > 1 ? ' votes' : ' vote') + ') ' + (e.vote_curr_rate > 0 ? 'You rated this: ' + e.vote_curr_rate + '' : '') + '
' 27 | 28 | $("#ajax_vote").html(str); //DISPLAYS THE NEW RATING IN HTML 29 | }, 30 | error: function (e) { 31 | console.log(e); 32 | } 33 | }); 34 | }).on("mouseout", function () { //WHEN MOUSE IS NOT OVER THE RATING 35 | $(".rating").show(); //SHOWS THE CURRENT RATING 36 | $(".transparent .star").css({"opacity": "0.25"}); //TRANSPARENTS THE BASE 37 | }); 38 | }); -------------------------------------------------------------------------------- /python-flask-mysql-jquery-ajax-star-rating-system/templates/star-rate-vote.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Star Rating/Voting System using Python Flask MySQL AJAX 6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 |
14 |
15 |

16 | This is a sample blog content 17 |

18 |

19 | Posted By: roytuts.com, 20 | Posted On: 25-08-2015 21 |

22 | 23 |
24 |
25 |
26 | {% if overall_rate > 0 %} 27 | {% for i in range(1, overall_rate + 1) %} 28 |
29 | {% endfor %} 30 | {% endif %} 31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
{{overall_dec_rate}}/5, {{overall_rows if overall_rows > 0 else 0}} {{'votes' if overall_rows > 1 else 'vote' }} {% if ip_rate %}You rated this: {{ip_rate}}{% endif %}
39 |
40 |
41 |
42 |
43 |

44 | The topic of blogging seems to come up a lot in our social media training workshops. The benefits of a quality blog are obvious – fresh content is good for your readers and your rankings. Blogs are easy to set up and even easier to update. We often tell people that if they can use Microsoft Word… they can update a blog. 45 | 46 | As easy as they are to set up, they can be difficult to maintain. A good blog is filled with relevant, timely content that is updated on a regular basis. New bloggers often start out with a bang but then fizzle out when they realize that creating content can be challenging. 47 |

48 |
49 |
50 |
51 | 52 | -------------------------------------------------------------------------------- /python-flask-rest-api-file-upload/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | UPLOAD_FOLDER = 'C:/uploads' 4 | 5 | app = Flask(__name__) 6 | #app.secret_key = "secret key" 7 | app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER 8 | app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 -------------------------------------------------------------------------------- /python-flask-rest-api-file-upload/main.py: -------------------------------------------------------------------------------- 1 | import os 2 | import urllib.request 3 | from app import app 4 | from flask import Flask, request, redirect, jsonify 5 | from werkzeug.utils import secure_filename 6 | 7 | ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) 8 | 9 | def allowed_file(filename): 10 | return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS 11 | 12 | @app.route('/file-upload', methods=['POST']) 13 | def upload_file(): 14 | # check if the post request has the file part 15 | if 'file' not in request.files: 16 | resp = jsonify({'message' : 'No file part in the request'}) 17 | resp.status_code = 400 18 | return resp 19 | file = request.files['file'] 20 | if file.filename == '': 21 | resp = jsonify({'message' : 'No file selected for uploading'}) 22 | resp.status_code = 400 23 | return resp 24 | if file and allowed_file(file.filename): 25 | filename = secure_filename(file.filename) 26 | file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) 27 | resp = jsonify({'message' : 'File successfully uploaded'}) 28 | resp.status_code = 201 29 | return resp 30 | else: 31 | resp = jsonify({'message' : 'Allowed file types are txt, pdf, png, jpg, jpeg, gif'}) 32 | resp.status_code = 400 33 | return resp 34 | 35 | if __name__ == "__main__": 36 | app.run() 37 | -------------------------------------------------------------------------------- /python-flask-rest-api-file-upload/readme.rst: -------------------------------------------------------------------------------- 1 | Please follow the tutorial https://roytuts.com/python-flask-rest-api-file-upload/ 2 | -------------------------------------------------------------------------------- /python-flask-rest-api-multiple-files-upload/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | UPLOAD_FOLDER = 'C:/uploads' 4 | 5 | app = Flask(__name__) 6 | #app.secret_key = "secret key" 7 | app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER 8 | app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 9 | -------------------------------------------------------------------------------- /python-flask-rest-api-multiple-files-upload/main.py: -------------------------------------------------------------------------------- 1 | import os 2 | import urllib.request 3 | from app import app 4 | from flask import Flask, request, redirect, jsonify 5 | from werkzeug.utils import secure_filename 6 | 7 | ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) 8 | 9 | def allowed_file(filename): 10 | return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS 11 | 12 | @app.route('/multiple-files-upload', methods=['POST']) 13 | def upload_file(): 14 | # check if the post request has the file part 15 | if 'files[]' not in request.files: 16 | resp = jsonify({'message' : 'No file part in the request'}) 17 | resp.status_code = 400 18 | return resp 19 | 20 | files = request.files.getlist('files[]') 21 | 22 | errors = {} 23 | success = False 24 | 25 | for file in files: 26 | if file and allowed_file(file.filename): 27 | filename = secure_filename(file.filename) 28 | file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) 29 | success = True 30 | else: 31 | errors[file.filename] = 'File type is not allowed' 32 | 33 | if success and errors: 34 | errors['message'] = 'File(s) successfully uploaded' 35 | resp = jsonify(errors) 36 | resp.status_code = 206 37 | return resp 38 | if success: 39 | resp = jsonify({'message' : 'Files successfully uploaded'}) 40 | resp.status_code = 201 41 | return resp 42 | else: 43 | resp = jsonify(errors) 44 | resp.status_code = 400 45 | return resp 46 | 47 | if __name__ == "__main__": 48 | app.run() 49 | -------------------------------------------------------------------------------- /python-flask-rest-api-multiple-files-upload/readme.rst: -------------------------------------------------------------------------------- 1 | Please follow the tutorial https://roytuts.com/python-flask-rest-api-multiple-files-upload/ 2 | -------------------------------------------------------------------------------- /python-flask-rest-api-multiple-response-formats/app.py: -------------------------------------------------------------------------------- 1 | import rest 2 | import json 3 | from simplexml import dumps 4 | from flask import Flask, make_response 5 | from flask_restful import Api 6 | 7 | app = Flask(__name__) 8 | 9 | api = Api(app) 10 | #api = Api(app, default_mediatype='application/json') 11 | 12 | @api.representation('application/json') 13 | def output_json(data, code, headers=None): 14 | resp = make_response(json.dumps({'response' : data}), code) 15 | resp.headers.extend(headers or {}) 16 | return resp 17 | 18 | @api.representation('application/xml') 19 | def output_xml(data, code, headers=None): 20 | resp = make_response(dumps({'response' : data}), code) 21 | resp.headers.extend(headers or {}) 22 | return resp 23 | 24 | #api.representations['application/json'] = output_json 25 | #api.representations['application/xml'] = output_xml 26 | 27 | api.add_resource(rest.Greet, '/') 28 | api.add_resource(rest.GreetName, '/') 29 | 30 | if __name__ == "__main__": 31 | app.run() -------------------------------------------------------------------------------- /python-flask-rest-api-multiple-response-formats/readme.rst: -------------------------------------------------------------------------------- 1 | You can read tutorial at https://roytuts.com/how-to-return-different-response-formats-json-xml-in-flask-rest-api/ -------------------------------------------------------------------------------- /python-flask-rest-api-multiple-response-formats/rest.py: -------------------------------------------------------------------------------- 1 | from flask import request 2 | from flask_restful import Resource 3 | 4 | class Greet(Resource): 5 | 6 | def get(self): 7 | return {'message' : 'Hello, how are you?'} 8 | 9 | def post(self): 10 | req = request.get_json() 11 | print('req', req) 12 | return req, 201 13 | 14 | class GreetName(Resource): 15 | def get(self, name): 16 | return {'message' : 'Hello ' + name + ', how are you?'} -------------------------------------------------------------------------------- /python-flask-rest-api-mysql-crud/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from flask_cors import CORS, cross_origin 3 | 4 | app = Flask(__name__) 5 | CORS(app) -------------------------------------------------------------------------------- /python-flask-rest-api-mysql-crud/db.py: -------------------------------------------------------------------------------- 1 | from app import app 2 | from flaskext.mysql import MySQL 3 | 4 | mysql = MySQL() 5 | 6 | # MySQL configurations 7 | app.config['MYSQL_DATABASE_USER'] = 'root' 8 | app.config['MYSQL_DATABASE_PASSWORD'] = '' 9 | app.config['MYSQL_DATABASE_DB'] = 'roytuts' 10 | app.config['MYSQL_DATABASE_HOST'] = 'localhost' 11 | mysql.init_app(app) -------------------------------------------------------------------------------- /python-flask-rest-api-mysql-crud/main.py: -------------------------------------------------------------------------------- 1 | import pymysql 2 | from app import app 3 | from db_config import mysql 4 | from flask import jsonify 5 | from flask import flash, request 6 | from werkzeug import generate_password_hash, check_password_hash 7 | 8 | @app.route('/add', methods=['POST']) 9 | def add_user(): 10 | try: 11 | _json = request.json 12 | _name = _json['name'] 13 | _email = _json['email'] 14 | _password = _json['pwd'] 15 | # validate the received values 16 | if _name and _email and _password and request.method == 'POST': 17 | #do not save password as a plain text 18 | _hashed_password = generate_password_hash(_password) 19 | # save edits 20 | sql = "INSERT INTO tbl_user(user_name, user_email, user_password) VALUES(%s, %s, %s)" 21 | data = (_name, _email, _hashed_password,) 22 | conn = mysql.connect() 23 | cursor = conn.cursor() 24 | cursor.execute(sql, data) 25 | conn.commit() 26 | resp = jsonify('User added successfully!') 27 | resp.status_code = 200 28 | return resp 29 | else: 30 | return not_found() 31 | except Exception as e: 32 | print(e) 33 | finally: 34 | cursor.close() 35 | conn.close() 36 | 37 | @app.route('/users') 38 | def users(): 39 | try: 40 | conn = mysql.connect() 41 | cursor = conn.cursor(pymysql.cursors.DictCursor) 42 | cursor.execute("SELECT user_id id, user_name name, user_email email, user_password pwd FROM tbl_user") 43 | rows = cursor.fetchall() 44 | resp = jsonify(rows) 45 | resp.status_code = 200 46 | return resp 47 | except Exception as e: 48 | print(e) 49 | finally: 50 | cursor.close() 51 | conn.close() 52 | 53 | @app.route('/user/') 54 | def user(id): 55 | try: 56 | conn = mysql.connect() 57 | cursor = conn.cursor(pymysql.cursors.DictCursor) 58 | cursor.execute("SELECT user_id id, user_name name, user_email email, user_password pwd FROM tbl_user WHERE user_id=%s", id) 59 | row = cursor.fetchone() 60 | resp = jsonify(row) 61 | resp.status_code = 200 62 | return resp 63 | except Exception as e: 64 | print(e) 65 | finally: 66 | cursor.close() 67 | conn.close() 68 | 69 | @app.route('/update', methods=['PUT']) 70 | def update_user(): 71 | try: 72 | _json = request.json 73 | _id = _json['id'] 74 | _name = _json['name'] 75 | _email = _json['email'] 76 | _password = _json['pwd'] 77 | # validate the received values 78 | if _name and _email and _password and _id and request.method == 'PUT': 79 | #do not save password as a plain text 80 | _hashed_password = generate_password_hash(_password) 81 | # save edits 82 | sql = "UPDATE tbl_user SET user_name=%s, user_email=%s, user_password=%s WHERE user_id=%s" 83 | data = (_name, _email, _hashed_password, _id,) 84 | conn = mysql.connect() 85 | cursor = conn.cursor() 86 | cursor.execute(sql, data) 87 | conn.commit() 88 | resp = jsonify('User updated successfully!') 89 | resp.status_code = 200 90 | return resp 91 | else: 92 | return not_found() 93 | except Exception as e: 94 | print(e) 95 | finally: 96 | cursor.close() 97 | conn.close() 98 | 99 | @app.route('/delete/', methods=['DELETE']) 100 | def delete_user(id): 101 | try: 102 | conn = mysql.connect() 103 | cursor = conn.cursor() 104 | cursor.execute("DELETE FROM tbl_user WHERE user_id=%s", (id,)) 105 | conn.commit() 106 | resp = jsonify('User deleted successfully!') 107 | resp.status_code = 200 108 | return resp 109 | except Exception as e: 110 | print(e) 111 | finally: 112 | cursor.close() 113 | conn.close() 114 | 115 | @app.errorhandler(404) 116 | def not_found(error=None): 117 | message = { 118 | 'status': 404, 119 | 'message': 'Not Found: ' + request.url, 120 | } 121 | resp = jsonify(message) 122 | resp.status_code = 404 123 | 124 | return resp 125 | 126 | if __name__ == "__main__": 127 | app.run() -------------------------------------------------------------------------------- /python-flask-rest-api-mysql-crud/readme.rst: -------------------------------------------------------------------------------- 1 | Please follow the tutorial https://roytuts.com/flask-rest-api-mysql-crud-example/ 2 | -------------------------------------------------------------------------------- /python-flask-rest-api-mysql-crud/tbl_user.sql: -------------------------------------------------------------------------------- 1 | CREATE DATABASE IF NOT EXISTS `roytuts`; 2 | USE `roytuts`; 3 | 4 | CREATE TABLE IF NOT EXISTS `tbl_user` ( 5 | `user_id` bigint NOT NULL AUTO_INCREMENT, 6 | `user_name` varchar(45) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL, 7 | `user_email` varchar(45) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL, 8 | `user_password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL, 9 | PRIMARY KEY (`user_id`) 10 | ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; 11 | 12 | INSERT INTO `tbl_user` (`user_id`, `user_name`, `user_email`, `user_password`) VALUES 13 | (1, 'Soumitra Roy', 'contact@roytuts.com', 'pbkdf2:sha256:600000$903OlqZ3mj0aTdSG$4bc69b01c4b09750a3b7bab2ba647f8161790fbe5cc54a6dc46ab6a5459ee474'); 14 | -------------------------------------------------------------------------------- /python-flask-rest-api-query-param/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | from flask_cors import CORS 3 | 4 | app = Flask(__name__) 5 | CORS(app) -------------------------------------------------------------------------------- /python-flask-rest-api-query-param/db.py: -------------------------------------------------------------------------------- 1 | from app import app 2 | from flaskext.mysql import MySQL 3 | 4 | mysql = MySQL() 5 | 6 | # MySQL configurations 7 | app.config['MYSQL_DATABASE_USER'] = 'root' 8 | app.config['MYSQL_DATABASE_PASSWORD'] = 'root' 9 | app.config['MYSQL_DATABASE_DB'] = 'roytuts' 10 | app.config['MYSQL_DATABASE_HOST'] = 'localhost' 11 | mysql.init_app(app) -------------------------------------------------------------------------------- /python-flask-rest-api-query-param/readme.rst: -------------------------------------------------------------------------------- 1 | You can go through the tutorial https://roytuts.com/query-parameter-in-rest-api-get-request-with-python-flask/ -------------------------------------------------------------------------------- /python-flask-rest-api-query-param/rest.py: -------------------------------------------------------------------------------- 1 | import pymysql 2 | from app import app 3 | from db import mysql 4 | from flask import jsonify, request 5 | 6 | @app.route('/user') 7 | def get_user(): 8 | conn = None; 9 | cursor = None; 10 | try: 11 | id = request.args.get('id') 12 | if id: 13 | conn = mysql.connect() 14 | cursor = conn.cursor(pymysql.cursors.DictCursor) 15 | cursor.execute("SELECT user_id id, user_name name, user_email email, user_password pwd FROM user WHERE user_id=%s", id) 16 | row = cursor.fetchone() 17 | resp = jsonify(row) 18 | resp.status_code = 200 19 | return resp 20 | else: 21 | resp = jsonify('User "id" not found in query string') 22 | resp.status_code = 500 23 | return resp 24 | except Exception as e: 25 | print(e) 26 | finally: 27 | cursor.close() 28 | conn.close() 29 | 30 | if __name__ == "__main__": 31 | app.run() -------------------------------------------------------------------------------- /python-flask-session/main.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, session, render_template 2 | 3 | app = Flask(__name__) 4 | app.secret_key = "secret key" 5 | 6 | @app.route('/') 7 | def app_session(): 8 | #session['msg'] = 'Hello' 9 | session.modified = True 10 | 11 | #session['msg'] = 'Hello, Soumitra' 12 | #print(session.get('msg')) 13 | 14 | #session.pop('msg') 15 | #print(session.get('msg')) 16 | 17 | #session['hi'] = 'Hi' 18 | #session['hello'] = 'Hello' 19 | 20 | #for key, val in session.items(): 21 | #print(key + ' -> ' + val) 22 | #print(key, ' -> ', val) 23 | 24 | #session.clear() 25 | 26 | #itemArray = {'name' : 'Soumitra', 'email' : 'soumitra@roytuts.com', 'address' : 'Earth'} 27 | #session['item'] = itemArray 28 | 29 | #if 'item' in session: 30 | # session['item'].pop('name') 31 | 32 | #session.pop('item') 33 | 34 | #if 'item' in session: 35 | # for key, val in session['item'].items(): 36 | # print(key + ' -> ' + val) 37 | 38 | itemNestedArray = { 'key' : {'name' : 'Soumitra', 'email' : 'soumitra@roytuts.com', 'address' : 'Earth'}} 39 | session['item'] = itemNestedArray 40 | 41 | if 'item' in session: 42 | for item in session['item'].items(): 43 | print(item) 44 | 45 | session['item'].pop('key') 46 | 47 | if 'item' in session: 48 | for item in session['item'].items(): 49 | print(item) 50 | 51 | return render_template('template.html') 52 | 53 | 54 | if __name__ == "__main__": 55 | app.run() -------------------------------------------------------------------------------- /python-flask-session/readme.rst: -------------------------------------------------------------------------------- 1 | You can go through the tutorial https://roytuts.com/session-management-in-python-flask -------------------------------------------------------------------------------- /python-flask-session/templates/template.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Python Flask Session Management 5 | 6 | 7 |
8 | {% if 'msg' in session %} 9 | {{ session['msg'] }} 10 | {% endif %} 11 |
12 | 13 | -------------------------------------------------------------------------------- /python-flask-templates/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | app = Flask(__name__) -------------------------------------------------------------------------------- /python-flask-templates/main.py: -------------------------------------------------------------------------------- 1 | from app import app 2 | from flask import render_template 3 | from datetime import datetime 4 | 5 | @app.context_processor 6 | def inject_now(): 7 | return {'now': datetime.utcnow()} 8 | 9 | @app.route('/') 10 | def home(): 11 | return render_template('index.html') 12 | 13 | @app.route('/about') 14 | def about(): 15 | return render_template('about.html') 16 | 17 | @app.route('/testimonials') 18 | def testimonials(): 19 | return render_template('testimonials.html') 20 | 21 | @app.route('/contact') 22 | def contact(): 23 | return render_template('contact.html') 24 | 25 | @app.route('/products') 26 | def products(): 27 | return render_template('products.html') 28 | 29 | if __name__ == "__main__": 30 | app.run() -------------------------------------------------------------------------------- /python-flask-templates/readme.rst: -------------------------------------------------------------------------------- 1 | Please follow the tutorial at https://roytuts.com/working-with-parent-and-child-templates-in-flask/ 2 | -------------------------------------------------------------------------------- /python-flask-templates/static/css/contact.css: -------------------------------------------------------------------------------- 1 | /* Style inputs with type="text", select elements and textareas */ 2 | input[type=text], select, textarea { 3 | width: 100%; /* Full width */ 4 | padding: 12px; /* Some padding */ 5 | border: 1px solid #ccc; /* Gray border */ 6 | border-radius: 4px; /* Rounded borders */ 7 | box-sizing: border-box; /* Make sure that padding and width stays in place */ 8 | margin-top: 6px; /* Add a top margin */ 9 | margin-bottom: 16px; /* Bottom margin */ 10 | resize: vertical /* Allow the user to vertically resize the textarea (not horizontally) */ 11 | } 12 | 13 | /* Style the submit button with a specific background color etc */ 14 | input[type=submit] { 15 | background-color: #66ccff; 16 | color: #000000; 17 | padding: 12px 20px; 18 | border: none; 19 | border-radius: 4px; 20 | cursor: pointer; 21 | } 22 | 23 | /* When moving the mouse over the submit button, add a darker green color */ 24 | input[type=submit]:hover { 25 | background-color:#0099cc; 26 | } 27 | 28 | /* Add a background color and some padding around the form */ 29 | .container { 30 | border-radius: 5px; 31 | background-color: #000000; 32 | padding: 20px; 33 | } -------------------------------------------------------------------------------- /python-flask-templates/static/css/main.css: -------------------------------------------------------------------------------- 1 | * { 2 | box-sizing: border-box; 3 | } 4 | 5 | .row::after { 6 | content: ""; 7 | clear: both; 8 | display: table; 9 | } 10 | 11 | [class*="col-"] { 12 | float: left; 13 | padding: 15px; 14 | } 15 | 16 | html { 17 | font-family: "Lucida Sans", sans-serif; 18 | } 19 | 20 | .header { 21 | background-color: #66ccff; 22 | color: #000000; 23 | padding: 15px; 24 | height: 75px; 25 | } 26 | .header-links{ 27 | padding:4px !important; 28 | } 29 | 30 | .menu-ul { 31 | list-style-type: none; 32 | margin: 0; 33 | padding: 0; 34 | color: #000000; 35 | 36 | } 37 | 38 | .menu-li { 39 | padding: 8px; 40 | margin-bottom: 7px; 41 | background-color: #66ccff; 42 | color: #000000; 43 | box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24); 44 | } 45 | 46 | .menu-li:hover { 47 | background-color: #0099cc; 48 | } 49 | 50 | .menu-li a{ 51 | text-decoration:none !important; 52 | color: #000000; 53 | } 54 | 55 | .aside { 56 | background-color: #33b5e5; 57 | padding: 15px; 58 | color: #000000; 59 | text-align: center; 60 | font-size: 14px; 61 | box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24); 62 | } 63 | 64 | .footer { 65 | background-color: #66ccff; 66 | color: #000000; 67 | text-align: center; 68 | font-size: 12px; 69 | padding: 15px; 70 | position: absolute; 71 | bottom: 0; 72 | width: 100%; 73 | height: 60px; 74 | /* Height of the footer */ 75 | } 76 | 77 | /* For mobile phones: */ 78 | [class*="col-"] { 79 | width: 100%; 80 | } 81 | 82 | @media only screen and (min-width: 600px) { 83 | 84 | /* For tablets: */ 85 | .col-s-1 { 86 | width: 8.33%; 87 | } 88 | 89 | .col-s-2 { 90 | width: 16.66%; 91 | } 92 | 93 | .col-s-3 { 94 | width: 25%; 95 | } 96 | 97 | .col-s-4 { 98 | width: 33.33%; 99 | } 100 | 101 | .col-s-5 { 102 | width: 41.66%; 103 | } 104 | 105 | .col-s-6 { 106 | width: 50%; 107 | } 108 | 109 | .col-s-7 { 110 | width: 58.33%; 111 | } 112 | 113 | .col-s-8 { 114 | width: 66.66%; 115 | } 116 | 117 | .col-s-9 { 118 | width: 75%; 119 | } 120 | 121 | .col-s-10 { 122 | width: 83.33%; 123 | } 124 | 125 | .col-s-11 { 126 | width: 91.66%; 127 | } 128 | 129 | .col-s-12 { 130 | width: 100%; 131 | } 132 | 133 | .hamburger { 134 | display: block; 135 | } 136 | 137 | } 138 | 139 | @media only screen and (min-width: 768px) { 140 | 141 | /* For desktop: */ 142 | .col-1 { 143 | width: 8.33%; 144 | } 145 | 146 | .col-2 { 147 | width: 16.66%; 148 | } 149 | 150 | .col-3 { 151 | width: 25%; 152 | } 153 | 154 | .col-4 { 155 | width: 33.33%; 156 | } 157 | 158 | .col-5 { 159 | width: 41.66%; 160 | } 161 | 162 | .col-6 { 163 | width: 50%; 164 | } 165 | 166 | .col-7 { 167 | width: 58.33%; 168 | } 169 | 170 | .col-8 { 171 | width: 66.66%; 172 | } 173 | 174 | .col-9 { 175 | width: 75%; 176 | } 177 | 178 | .col-10 { 179 | width: 83.33%; 180 | } 181 | 182 | .col-11 { 183 | width: 91.66%; 184 | } 185 | 186 | .col-12 { 187 | width: 100%; 188 | } 189 | } 190 | 191 | .navbar { 192 | height: 60px; 193 | width: 100%; 194 | background-color: #FF4E00; 195 | } 196 | 197 | span { 198 | display: block; 199 | color: white; 200 | text-align: center; 201 | float: left; 202 | padding: 14px 16px 203 | } 204 | 205 | ul { 206 | list-style-type: none; 207 | margin: 0; 208 | padding: 0; 209 | overflow: hidden; 210 | } 211 | 212 | li { 213 | float: left; 214 | } 215 | 216 | li a { 217 | display: block; 218 | color: black; 219 | text-align: center; 220 | padding: 14px 16px; 221 | text-decoration: none; 222 | } 223 | 224 | li a:hover { 225 | color: black; 226 | cursor: pointer 227 | } 228 | 229 | @media screen and (max-width: 600px) { 230 | .header-links { 231 | display: none; 232 | } 233 | 234 | .hamburger { 235 | display: block; 236 | } 237 | 238 | .footer { 239 | position: relative; 240 | } 241 | 242 | } -------------------------------------------------------------------------------- /python-flask-templates/static/images/gentleman.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roytuts/flask/b5efbaf7d72c59765f0f29c18d9a83fde78e5d12/python-flask-templates/static/images/gentleman.png -------------------------------------------------------------------------------- /python-flask-templates/static/images/lady.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roytuts/flask/b5efbaf7d72c59765f0f29c18d9a83fde78e5d12/python-flask-templates/static/images/lady.png -------------------------------------------------------------------------------- /python-flask-templates/templates/about.html: -------------------------------------------------------------------------------- 1 | {% extends "parent.html" %} 2 | {% block title %}About Us{% endblock %} 3 | {% block content %} 4 |

About Us

5 |

6 | This is about us page. 7 |

8 | {% endblock %} -------------------------------------------------------------------------------- /python-flask-templates/templates/contact.html: -------------------------------------------------------------------------------- 1 | {% extends "parent.html" %} 2 | {% block title %}Contact Us{% endblock %} 3 | {% block head %} 4 | 5 | {% endblock %} 6 | {% block content %} 7 | 13 | 14 |
15 |

Contact Us

16 |

Use the form below to leave us a message:

17 |
18 | 19 |
20 |
21 |
22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 |
31 | {% endblock %} -------------------------------------------------------------------------------- /python-flask-templates/templates/index.html: -------------------------------------------------------------------------------- 1 | {% extends "parent.html" %} 2 | {% block title %}Welcome{% endblock %} 3 | {% block content %} 4 |

Welcome

5 |

6 | Welcome to working with parent and child templates in flask 7 |

8 | {% endblock %} -------------------------------------------------------------------------------- /python-flask-templates/templates/parent.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Parent and Child Templates in Flask - {% block title %}{% endblock %} 6 | 7 | 8 | 9 | {% block head %}{% endblock %} 10 | 11 | 12 | 13 | {% include "snippets/header.html" %} 14 | 15 |
16 | 17 | {% include "snippets/left.html" %} 18 | 19 |
20 | 21 | {% block content %}{% endblock %} 22 | 23 |
24 | 25 |
26 | 27 | {% include "snippets/footer.html" %} 28 | 29 | 30 | -------------------------------------------------------------------------------- /python-flask-templates/templates/products.html: -------------------------------------------------------------------------------- 1 | {% extends "parent.html" %} 2 | {% block title %}Our Products{% endblock %} 3 | {% block head %} 4 | 5 | {% endblock %} 6 | {% block content %} 7 |

Our Products

8 |

This is a product page

9 | {% endblock %} -------------------------------------------------------------------------------- /python-flask-templates/templates/snippets/footer.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /python-flask-templates/templates/snippets/header.html: -------------------------------------------------------------------------------- 1 |
2 | 7 |
-------------------------------------------------------------------------------- /python-flask-templates/templates/snippets/left.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /python-flask-templates/templates/testimonials.html: -------------------------------------------------------------------------------- 1 | {% extends "parent.html" %} 2 | {% block title %}Testimonials{% endblock %} 3 | {% block content %} 4 |

Read what others have to say

5 |

Should have testimonials

6 | {% endblock %} -------------------------------------------------------------------------------- /python-flask-upload-display-image/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | UPLOAD_FOLDER = 'static/uploads/' 4 | 5 | app = Flask(__name__) 6 | app.secret_key = "secret key" 7 | app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER 8 | app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 -------------------------------------------------------------------------------- /python-flask-upload-display-image/main.py: -------------------------------------------------------------------------------- 1 | import os 2 | from app import app 3 | import urllib.request 4 | from flask import Flask, flash, request, redirect, url_for, render_template 5 | from werkzeug.utils import secure_filename 6 | 7 | ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif']) 8 | 9 | def allowed_file(filename): 10 | return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS 11 | 12 | @app.route('/') 13 | def upload_form(): 14 | return render_template('upload.html') 15 | 16 | @app.route('/', methods=['POST']) 17 | def upload_image(): 18 | if 'file' not in request.files: 19 | flash('No file part') 20 | return redirect(request.url) 21 | file = request.files['file'] 22 | if file.filename == '': 23 | flash('No image selected for uploading') 24 | return redirect(request.url) 25 | if file and allowed_file(file.filename): 26 | filename = secure_filename(file.filename) 27 | file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) 28 | #print('upload_image filename: ' + filename) 29 | flash('Image successfully uploaded and displayed below') 30 | return render_template('upload.html', filename=filename) 31 | else: 32 | flash('Allowed image types are -> png, jpg, jpeg, gif') 33 | return redirect(request.url) 34 | 35 | @app.route('/display/') 36 | def display_image(filename): 37 | #print('display_image filename: ' + filename) 38 | return redirect(url_for('static', filename='uploads/' + filename), code=301) 39 | 40 | if __name__ == "__main__": 41 | app.run() -------------------------------------------------------------------------------- /python-flask-upload-display-image/readme.rst: -------------------------------------------------------------------------------- 1 | Please follow the tutorial https://roytuts.com/upload-and-display-image-using-python-flask/ 2 | -------------------------------------------------------------------------------- /python-flask-upload-display-image/static/uploads/sample.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roytuts/flask/b5efbaf7d72c59765f0f29c18d9a83fde78e5d12/python-flask-upload-display-image/static/uploads/sample.jpg -------------------------------------------------------------------------------- /python-flask-upload-display-image/templates/upload.html: -------------------------------------------------------------------------------- 1 | 2 | Python Flask Image Upload and Display Example 3 |

Select an image to upload and display

4 |

5 | {% with messages = get_flashed_messages() %} 6 | {% if messages %} 7 |

    8 | {% for message in messages %} 9 |
  • {{ message }}
  • 10 | {% endfor %} 11 |
12 | {% endif %} 13 | {% endwith %} 14 |

15 | {% if filename %} 16 |
17 | 18 |
19 | {% endif %} 20 |
21 |
22 |

23 | 24 |

25 |
26 |

27 | 28 |

29 |
-------------------------------------------------------------------------------- /python-flask-upload-display-multiple-images/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | UPLOAD_FOLDER = 'static/uploads/' 4 | 5 | app = Flask(__name__) 6 | app.secret_key = "secret key" 7 | app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER 8 | app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 -------------------------------------------------------------------------------- /python-flask-upload-display-multiple-images/main.py: -------------------------------------------------------------------------------- 1 | import os 2 | from app import app 3 | import urllib.request 4 | from werkzeug.utils import secure_filename 5 | from flask import Flask, flash, request, redirect, url_for, render_template 6 | 7 | ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif']) 8 | 9 | def allowed_file(filename): 10 | return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS 11 | 12 | @app.route('/') 13 | def upload_form(): 14 | return render_template('upload.html') 15 | 16 | @app.route('/', methods=['POST']) 17 | def upload_image(): 18 | if 'files[]' not in request.files: 19 | flash('No file part') 20 | return redirect(request.url) 21 | files = request.files.getlist('files[]') 22 | file_names = [] 23 | for file in files: 24 | if file and allowed_file(file.filename): 25 | filename = secure_filename(file.filename) 26 | file_names.append(filename) 27 | file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) 28 | #else: 29 | # flash('Allowed image types are -> png, jpg, jpeg, gif') 30 | # return redirect(request.url) 31 | 32 | return render_template('upload.html', filenames=file_names) 33 | 34 | @app.route('/display/') 35 | def display_image(filename): 36 | #print('display_image filename: ' + filename) 37 | return redirect(url_for('static', filename='uploads/' + filename), code=301) 38 | 39 | if __name__ == "__main__": 40 | app.run() -------------------------------------------------------------------------------- /python-flask-upload-display-multiple-images/readme.rst: -------------------------------------------------------------------------------- 1 | Please follow the tutorial https://roytuts.com/upload-and-display-multiple-images-using-python-and-flask/ 2 | -------------------------------------------------------------------------------- /python-flask-upload-display-multiple-images/static/uploads/nature-car.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roytuts/flask/b5efbaf7d72c59765f0f29c18d9a83fde78e5d12/python-flask-upload-display-multiple-images/static/uploads/nature-car.jpg -------------------------------------------------------------------------------- /python-flask-upload-display-multiple-images/static/uploads/sample.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roytuts/flask/b5efbaf7d72c59765f0f29c18d9a83fde78e5d12/python-flask-upload-display-multiple-images/static/uploads/sample.jpg -------------------------------------------------------------------------------- /python-flask-upload-display-multiple-images/templates/upload.html: -------------------------------------------------------------------------------- 1 | 2 | Python Flask Upload Multiple Images and Display them 3 |

Select multiple images to upload and display

4 |

5 | {% with messages = get_flashed_messages() %} 6 | {% if messages %} 7 |

    8 | {% for message in messages %} 9 |
  • {{ message }}
  • 10 | {% endfor %} 11 |
12 | {% endif %} 13 | {% endwith %} 14 |

15 | 16 |
17 |
18 |

19 | 20 |

21 |
22 |

23 | 24 |

25 |
26 | 27 | {% if filenames %} 28 | {% for filename in filenames %} 29 |
30 | 31 |
32 | {% endfor %} 33 | {% endif %} -------------------------------------------------------------------------------- /python-flask-upload-play-video/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | UPLOAD_FOLDER = 'static/uploads/' 4 | 5 | app = Flask(__name__) 6 | app.secret_key = "secret key" 7 | app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER 8 | app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 -------------------------------------------------------------------------------- /python-flask-upload-play-video/main.py: -------------------------------------------------------------------------------- 1 | import os 2 | from app import app 3 | import urllib.request 4 | from flask import Flask, flash, request, redirect, url_for, render_template 5 | from werkzeug.utils import secure_filename 6 | 7 | @app.route('/') 8 | def upload_form(): 9 | return render_template('upload.html') 10 | 11 | @app.route('/', methods=['POST']) 12 | def upload_video(): 13 | if 'file' not in request.files: 14 | flash('No file part') 15 | return redirect(request.url) 16 | file = request.files['file'] 17 | if file.filename == '': 18 | flash('No image selected for uploading') 19 | return redirect(request.url) 20 | else: 21 | filename = secure_filename(file.filename) 22 | file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) 23 | #print('upload_video filename: ' + filename) 24 | flash('Video successfully uploaded and displayed below') 25 | return render_template('upload.html', filename=filename) 26 | 27 | @app.route('/display/') 28 | def display_video(filename): 29 | #print('display_video filename: ' + filename) 30 | return redirect(url_for('static', filename='uploads/' + filename), code=301) 31 | 32 | if __name__ == "__main__": 33 | app.run() -------------------------------------------------------------------------------- /python-flask-upload-play-video/readme.rst: -------------------------------------------------------------------------------- 1 | You can read tutorial at https://roytuts.com/upload-and-play-video-using-flask/ -------------------------------------------------------------------------------- /python-flask-upload-play-video/static/uploads/earth.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roytuts/flask/b5efbaf7d72c59765f0f29c18d9a83fde78e5d12/python-flask-upload-play-video/static/uploads/earth.mp4 -------------------------------------------------------------------------------- /python-flask-upload-play-video/templates/upload.html: -------------------------------------------------------------------------------- 1 | 2 | Python Flask - Video Upload and Play Example 3 |

Select a video to upload and play

4 |

5 | {% with messages = get_flashed_messages() %} 6 | {% if messages %} 7 |

    8 | {% for message in messages %} 9 |
  • {{ message }}
  • 10 | {% endfor %} 11 |
12 | {% endif %} 13 | {% endwith %} 14 |

15 | {% if filename %} 16 |
17 | 20 |
21 | {% endif %} 22 |
23 |
24 |

25 | 26 |

27 |
28 |

29 | 30 |

31 |
-------------------------------------------------------------------------------- /python_flask_file_upload/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | UPLOAD_FOLDER = 'D:/uploads' 4 | 5 | app = Flask(__name__) 6 | app.secret_key = "secret key" 7 | app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER 8 | app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 9 | -------------------------------------------------------------------------------- /python_flask_file_upload/main.py: -------------------------------------------------------------------------------- 1 | import os 2 | #import magic 3 | import urllib.request 4 | from app import app 5 | from flask import Flask, flash, request, redirect, render_template 6 | from werkzeug.utils import secure_filename 7 | 8 | ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) 9 | 10 | def allowed_file(filename): 11 | return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS 12 | 13 | @app.route('/') 14 | def upload_form(): 15 | return render_template('upload.html') 16 | 17 | @app.route('/', methods=['POST']) 18 | def upload_file(): 19 | if request.method == 'POST': 20 | # check if the post request has the file part 21 | if 'file' not in request.files: 22 | flash('No file part') 23 | return redirect(request.url) 24 | file = request.files['file'] 25 | if file.filename == '': 26 | flash('No file selected for uploading') 27 | return redirect(request.url) 28 | if file and allowed_file(file.filename): 29 | filename = secure_filename(file.filename) 30 | file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) 31 | flash('File successfully uploaded') 32 | return redirect('/') 33 | else: 34 | flash('Allowed file types are txt, pdf, png, jpg, jpeg, gif') 35 | return redirect(request.url) 36 | 37 | if __name__ == "__main__": 38 | app.run() 39 | -------------------------------------------------------------------------------- /python_flask_file_upload/readme.rst: -------------------------------------------------------------------------------- 1 | You can go through the tutorial https://www.roytuts.com/python-flask-file-upload-example/ 2 | -------------------------------------------------------------------------------- /python_flask_file_upload/templates/upload.html: -------------------------------------------------------------------------------- 1 | 2 | Python Flask File Upload Example 3 |

Select a file to upload

4 |

5 | {% with messages = get_flashed_messages() %} 6 | {% if messages %} 7 |

    8 | {% for message in messages %} 9 |
  • {{ message }}
  • 10 | {% endfor %} 11 |
12 | {% endif %} 13 | {% endwith %} 14 |

15 |
16 |
17 |

18 | 19 |

20 |
21 |

22 | 23 |

24 |
25 | -------------------------------------------------------------------------------- /python_flask_mysql_shopping_cart/app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask 2 | 3 | app = Flask(__name__) 4 | app.secret_key = "secret key" -------------------------------------------------------------------------------- /python_flask_mysql_shopping_cart/db_config.py: -------------------------------------------------------------------------------- 1 | from app import app 2 | from flaskext.mysql import MySQL 3 | 4 | mysql = MySQL() 5 | 6 | # MySQL configurations 7 | app.config['MYSQL_DATABASE_USER'] = 'root' 8 | app.config['MYSQL_DATABASE_PASSWORD'] = 'root' 9 | app.config['MYSQL_DATABASE_DB'] = 'roytuts' 10 | app.config['MYSQL_DATABASE_HOST'] = 'localhost' 11 | mysql.init_app(app) -------------------------------------------------------------------------------- /python_flask_mysql_shopping_cart/main.py: -------------------------------------------------------------------------------- 1 | import pymysql 2 | from app import app 3 | from db_config import mysql 4 | from flask import flash, session, render_template, request, redirect, url_for 5 | #from werkzeug import generate_password_hash, check_password_hash 6 | from werkzeug.security import generate_password_hash, check_password_hash 7 | 8 | @app.route('/add', methods=['POST']) 9 | def add_product_to_cart(): 10 | cursor = None 11 | try: 12 | _quantity = int(request.form['quantity']) 13 | _code = request.form['code'] 14 | # validate the received values 15 | if _quantity and _code and request.method == 'POST': 16 | conn = mysql.connect() 17 | cursor = conn.cursor(pymysql.cursors.DictCursor) 18 | cursor.execute("SELECT * FROM product WHERE code=%s", _code) 19 | row = cursor.fetchone() 20 | 21 | itemArray = { row['code'] : {'name' : row['name'], 'code' : row['code'], 'quantity' : _quantity, 'price' : row['price'], 'image' : row['image'], 'total_price': _quantity * row['price']}} 22 | 23 | all_total_price = 0 24 | all_total_quantity = 0 25 | 26 | session.modified = True 27 | if 'cart_item' in session: 28 | if row['code'] in session['cart_item']: 29 | for key, value in session['cart_item'].items(): 30 | if row['code'] == key: 31 | #session.modified = True 32 | #if session['cart_item'][key]['quantity'] is not None: 33 | # session['cart_item'][key]['quantity'] = 0 34 | old_quantity = session['cart_item'][key]['quantity'] 35 | total_quantity = old_quantity + _quantity 36 | session['cart_item'][key]['quantity'] = total_quantity 37 | session['cart_item'][key]['total_price'] = total_quantity * row['price'] 38 | else: 39 | session['cart_item'] = array_merge(session['cart_item'], itemArray) 40 | 41 | for key, value in session['cart_item'].items(): 42 | individual_quantity = int(session['cart_item'][key]['quantity']) 43 | individual_price = float(session['cart_item'][key]['total_price']) 44 | all_total_quantity = all_total_quantity + individual_quantity 45 | all_total_price = all_total_price + individual_price 46 | else: 47 | session['cart_item'] = itemArray 48 | all_total_quantity = all_total_quantity + _quantity 49 | all_total_price = all_total_price + _quantity * row['price'] 50 | 51 | session['all_total_quantity'] = all_total_quantity 52 | session['all_total_price'] = all_total_price 53 | 54 | return redirect(url_for('.products')) 55 | else: 56 | return 'Error while adding item to cart' 57 | except Exception as e: 58 | print(e) 59 | finally: 60 | cursor.close() 61 | conn.close() 62 | 63 | @app.route('/') 64 | def products(): 65 | try: 66 | conn = mysql.connect() 67 | cursor = conn.cursor(pymysql.cursors.DictCursor) 68 | cursor.execute("SELECT * FROM product") 69 | rows = cursor.fetchall() 70 | return render_template('products.html', products=rows) 71 | except Exception as e: 72 | print(e) 73 | finally: 74 | cursor.close() 75 | conn.close() 76 | 77 | @app.route('/empty') 78 | def empty_cart(): 79 | try: 80 | session.clear() 81 | return redirect(url_for('.products')) 82 | except Exception as e: 83 | print(e) 84 | 85 | @app.route('/delete/') 86 | def delete_product(code): 87 | try: 88 | all_total_price = 0 89 | all_total_quantity = 0 90 | session.modified = True 91 | 92 | for item in session['cart_item'].items(): 93 | if item[0] == code: 94 | session['cart_item'].pop(item[0], None) 95 | if 'cart_item' in session: 96 | for key, value in session['cart_item'].items(): 97 | individual_quantity = int(session['cart_item'][key]['quantity']) 98 | individual_price = float(session['cart_item'][key]['total_price']) 99 | all_total_quantity = all_total_quantity + individual_quantity 100 | all_total_price = all_total_price + individual_price 101 | break 102 | 103 | if all_total_quantity == 0: 104 | session.clear() 105 | else: 106 | session['all_total_quantity'] = all_total_quantity 107 | session['all_total_price'] = all_total_price 108 | 109 | #return redirect('/') 110 | return redirect(url_for('.products')) 111 | except Exception as e: 112 | print(e) 113 | 114 | def array_merge( first_array , second_array ): 115 | if isinstance( first_array , list ) and isinstance( second_array , list ): 116 | return first_array + second_array 117 | elif isinstance( first_array , dict ) and isinstance( second_array , dict ): 118 | return dict( list( first_array.items() ) + list( second_array.items() ) ) 119 | elif isinstance( first_array , set ) and isinstance( second_array , set ): 120 | return first_array.union( second_array ) 121 | return False 122 | 123 | if __name__ == "__main__": 124 | app.run() -------------------------------------------------------------------------------- /python_flask_mysql_shopping_cart/readme.rst: -------------------------------------------------------------------------------- 1 | You can read tutorial https://roytuts.com/simple-shopping-cart-using-python-flask-mysql/ -------------------------------------------------------------------------------- /python_flask_mysql_shopping_cart/static/css/style.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: Arial; 3 | color: #211a1a; 4 | font-size: 0.9em; 5 | } 6 | 7 | #shopping-cart { 8 | margin: 40px; 9 | } 10 | 11 | #product-grid { 12 | margin: 40px; 13 | } 14 | 15 | #shopping-cart table { 16 | width: 100%; 17 | background-color: #F0F0F0; 18 | } 19 | 20 | #shopping-cart table td { 21 | background-color: #FFFFFF; 22 | } 23 | 24 | .txt-heading { 25 | color: #211a1a; 26 | border-bottom: 1px solid #E0E0E0; 27 | overflow: auto; 28 | } 29 | 30 | #btnEmpty { 31 | background-color: #ffffff; 32 | border: #d00000 1px solid; 33 | padding: 5px 10px; 34 | color: #d00000; 35 | float: right; 36 | text-decoration: none; 37 | border-radius: 3px; 38 | margin: 10px 0px; 39 | } 40 | 41 | .btnAddAction { 42 | padding: 5px 10px; 43 | margin-left: 5px; 44 | background-color: #efefef; 45 | border: #E0E0E0 1px solid; 46 | color: #211a1a; 47 | float: right; 48 | text-decoration: none; 49 | border-radius: 3px; 50 | cursor: pointer; 51 | } 52 | 53 | #product-grid .txt-heading { 54 | margin-bottom: 18px; 55 | } 56 | 57 | .product-item { 58 | float: left; 59 | background: #ffffff; 60 | margin: 30px 30px 0px 0px; 61 | border: #E0E0E0 1px solid; 62 | } 63 | 64 | .product-image { 65 | height: 155px; 66 | width: 250px; 67 | background-color: #FFF; 68 | } 69 | 70 | .clear-float { 71 | clear: both; 72 | } 73 | 74 | .demo-input-box { 75 | border-radius: 2px; 76 | border: #CCC 1px solid; 77 | padding: 2px 1px; 78 | } 79 | 80 | .tbl-cart { 81 | font-size: 0.9em; 82 | } 83 | 84 | .tbl-cart th { 85 | font-weight: normal; 86 | } 87 | 88 | .product-title { 89 | margin-bottom: 20px; 90 | } 91 | 92 | .product-price { 93 | float:left; 94 | } 95 | 96 | .cart-action { 97 | float: right; 98 | } 99 | 100 | .product-quantity { 101 | padding: 5px 10px; 102 | border-radius: 3px; 103 | border: #E0E0E0 1px solid; 104 | } 105 | 106 | .product-tile-footer { 107 | padding: 15px 15px 0px 15px; 108 | overflow: auto; 109 | } 110 | 111 | .cart-item-image { 112 | width: 30px; 113 | height: 30px; 114 | border-radius: 50%; 115 | border: #E0E0E0 1px solid; 116 | padding: 5px; 117 | vertical-align: middle; 118 | margin-right: 15px; 119 | } 120 | .no-records { 121 | text-align: center; 122 | clear: both; 123 | margin: 38px 0px; 124 | } 125 | -------------------------------------------------------------------------------- /python_flask_mysql_shopping_cart/static/images/icon-delete.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roytuts/flask/b5efbaf7d72c59765f0f29c18d9a83fde78e5d12/python_flask_mysql_shopping_cart/static/images/icon-delete.png -------------------------------------------------------------------------------- /python_flask_mysql_shopping_cart/static/images/product-images/bag.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roytuts/flask/b5efbaf7d72c59765f0f29c18d9a83fde78e5d12/python_flask_mysql_shopping_cart/static/images/product-images/bag.jpg -------------------------------------------------------------------------------- /python_flask_mysql_shopping_cart/static/images/product-images/camera.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roytuts/flask/b5efbaf7d72c59765f0f29c18d9a83fde78e5d12/python_flask_mysql_shopping_cart/static/images/product-images/camera.jpg -------------------------------------------------------------------------------- /python_flask_mysql_shopping_cart/static/images/product-images/external-hard-drive.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roytuts/flask/b5efbaf7d72c59765f0f29c18d9a83fde78e5d12/python_flask_mysql_shopping_cart/static/images/product-images/external-hard-drive.jpg -------------------------------------------------------------------------------- /python_flask_mysql_shopping_cart/static/images/product-images/headphone.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roytuts/flask/b5efbaf7d72c59765f0f29c18d9a83fde78e5d12/python_flask_mysql_shopping_cart/static/images/product-images/headphone.jpg -------------------------------------------------------------------------------- /python_flask_mysql_shopping_cart/static/images/product-images/laptop.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roytuts/flask/b5efbaf7d72c59765f0f29c18d9a83fde78e5d12/python_flask_mysql_shopping_cart/static/images/product-images/laptop.jpg -------------------------------------------------------------------------------- /python_flask_mysql_shopping_cart/static/images/product-images/mobile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roytuts/flask/b5efbaf7d72c59765f0f29c18d9a83fde78e5d12/python_flask_mysql_shopping_cart/static/images/product-images/mobile.jpg -------------------------------------------------------------------------------- /python_flask_mysql_shopping_cart/static/images/product-images/shoes.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roytuts/flask/b5efbaf7d72c59765f0f29c18d9a83fde78e5d12/python_flask_mysql_shopping_cart/static/images/product-images/shoes.jpg -------------------------------------------------------------------------------- /python_flask_mysql_shopping_cart/static/images/product-images/watch.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/roytuts/flask/b5efbaf7d72c59765f0f29c18d9a83fde78e5d12/python_flask_mysql_shopping_cart/static/images/product-images/watch.jpg -------------------------------------------------------------------------------- /python_flask_mysql_shopping_cart/templates/products.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Python Flask Simple Shopping Cart 5 | 6 | 7 | 8 |
9 | {% with messages = get_flashed_messages() %} 10 | {% if messages %} 11 |
    12 | {% for message in messages %} 13 |
  • {{ message }}
  • 14 | {% endfor %} 15 |
16 | {% endif %} 17 | {% endwith %} 18 |
19 | 20 |
21 |
Shopping Cart
22 | {% if 'cart_item' in session %} 23 | Empty Cart 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | {% for key, val in session['cart_item'].items() %} 35 | {% set quantity = session['cart_item'][key]['quantity'] %} 36 | {% set price = session['cart_item'][key]['price'] %} 37 | {% set item_price = session['cart_item'][key]['total_price'] %} 38 | 39 | 40 | 41 | 42 | 43 | 44 | 49 | 50 | {% endfor %} 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 |
NameCodeQuantityUnit PricePriceRemove
{{ session['cart_item'][key]['name'] }}{{ session['cart_item'][key]['code'] }}{{ quantity }}₹ {{ price }}₹ {{ item_price }} 45 | 46 | Remove Item 47 | 48 |
Total:{{ session['all_total_quantity'] }}₹ {{ session['all_total_price'] }}
59 | {% else: %} 60 |
Your Cart is Empty
61 | {% endif %} 62 |
63 | 64 |
65 |
Products
66 | 67 | {% for product in products %} 68 | 69 |
70 |
71 |
72 | 81 |
82 |
83 | 84 | {% endfor %} 85 | 86 |
87 | 88 | 89 | --------------------------------------------------------------------------------