PythonWeb AppApp DevelopmentHTMLMySQLCSSJavaScript

 

This post is part of a series called Creating a Web App From Scratch Using Python Flask and MySQL.

Creating a Web App From Scratch Using Python Flask and MySQL: Part 2

In this series, we'll be using Python, Flask and MySQL to create a simple web application from scratch. It will be a simple bucket list application where users can register, sign in and create their bucket list.

This tutorial assumes that you have some basic knowledge of the Python programming language. We'll be using Flask, a Python web application framework, to create our application, with MySQL as the back end.

If you need to brush up on your Python skills, try the Introduction to Python course, which gives you a solid foundation in the language for just 17072.

Flask is a Python framework for creating web applications. From the official site,

Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions.

When we think about Python, the de facto framework that comes to our mind is the Django framework. But from a Python beginner's perspective, Flask is easier to get started with, when compared to Django.

Setting up Flask is pretty simple and quick. With pip package manager, all we need to do is: 

Once you're done with installing Flask, create a folder called FlaskApp. Navigate to the FlaskApp folder and create a file called app.py. Import the flask module and create an app using Flask as shown:

Now define the basic route / and its corresponding request handler:

Next, check if the executed file is the main program and run the app:

Save the changes and execute app.py:

Point your browser to http://localhost:5000/ and you should have the welcome message.

First, when the application runs we should show a home page with the latest bucket list items added by users. So let's add our home page to our application folder.

Flask looks for template files inside the templates folder. So navigate to the PythonApp folder and create a folder called templates. Inside templates, create a file called index.html. Open up index.html and add the following HTML:

Open up app.py and import render_template, which we'll use to render the template files.

Modify the main method to return the rendered template file.

Save the changes and restart the server. Point your browser to http://localhost:5000/ and you should have the below screen:

 

We'll be using MySQL as the back end. So log into MySQL from the command line, or if you prefer a GUI like MySQL work bench, you can use that too. First, create a database called BucketList. From the command line: 

Enter the required password and when logged in, execute the following command to create the database:

Once the database has been created, create  a table called tbl_user as shown:

We'll be using Stored procedures for our Python application to interact with the MySQL database. So, once the table tbl_user has been created, create a stored procedure called sp_createUser to sign up a user.

When creating a stored procedure to create a user in the tbl_user table, first we need to check if a user with the same username already exists. If it exists we need to throw an error to the user, otherwise we'll create the user in the user table. Here is how the stored procedure sp_createUser would look:

Navigate to the PythonApp/templates directory and create an HTML file called signup.html. Add the following HTML code to signup.html:

Also add the following CSS as signup.css to the static folder inside PythonApp.

In app.py add another method called showSignUp to render the signup page once a request comes to /showSignUp:

Save the changes and restart the server. Click on the Sign Up button on the home page and you should have the signup page as shown: 

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

Sign Up user page

Next, we need a server-side method for the UI to interact with the MySQL database. So navigate to PythonApp and open app.py. Create a new method called signUp and also add a route /signUp. Here is how it looks:

We'll be using jQuery AJAX to post our signup data to the signUp method, so we'll specify the method in the route definition.

In order to read the posted values we need to import request from Flask.

Using request we can read the posted values as shown below:

Once the values are read, we'll simply check if they are valid and for the time being let's just return a simple message:

Also import json from Flask, since we are using it in the above code to return json data.

We'll be using jQuery AJAX to send the signup request to the Python method. Download and place jQuery inside PythonApp/static/js and add a link to it from the signup page. Once jQuery has been included, we'll add a jQuery POST request when the user clicks the Sign Up button.

So, let's attach the signup button click event as shown:

Save all the changes and restart the server. From the Sign Up page, fill in the details and click Sign Up. Check the browser console and you should have the below message:

 

Once we have the name, email address and password, we can simply call the MySQL stored procedure to create the new user.

To connect with MySQL, we'll be using Flask-MySQL, which is a Flask extension. In order to get started with Flask-MySQL, install it using pip package manager:

Import MySQL inside app.py:

Earlier we defined our app as shown:

Along with that include the following MySQL configurations:

First, let's create the MySQL connection:

Once the connection is created, we'll require a cursor to query our stored procedure. So, using conn connection, create a cursor.

Before calling the create user stored procedure, let's make our password salted using a helper provided by Werkzeug. Import the module into app.py:

Use the salting module to create the hashed password.

Now, let's call the procedure sp_createUser:

If the procedure is executed successfully, then we'll commit the changes and return the success message. 

Save the changes and restart the server. Go to the signup page and enter the name, email address and password and click the Sign Up button. On successful user creation, you'll be able to see a message in your browser console.

In this tutorial, we saw how to get started with creating a web application using Python Flask, MySQL and the Flask-MySQL extension. We created and designed the database tables and stored procedure, and implemented the signup functionality. In the next tutorial, we'll take this series to the next level by implementing sign-in functionality and some other features.

Source code from this tutorial is available on GitHub.

Do let us know your thoughts in the comments below! 

 

[출처] http://code.tutsplus.com/tutorials/creating-a-web-app-from-scratch-using-python-flask-and-mysql--cms-22972

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
57 SQLAlchemy 시작하기 – Part 2 졸리운_곰 2016.06.11 539
56 SQLAlchemy 시작하기 – Part 1 졸리운_곰 2016.06.11 401
55 TensorFlow의 기본 사용법 졸리운_곰 2016.06.11 725
54 텐서플로우 시작하기 file 졸리운_곰 2016.06.11 774
53 Introduction to Python for Econometrics_Statistics and Data Analysis.pdf file 졸리운_곰 2016.06.07 2529
52 Numerical.Methods.in.Engineering.with.Python.2nd.Edition.Jaan.Kiusalaas.2010.pdf file 졸리운_곰 2016.06.07 2499
51 NumMethodPython.pdf file 졸리운_곰 2016.06.07 2419
50 Python-for-Computational-Science-and-Engineering.pdf file 졸리운_곰 2016.06.07 2316
» PythonWeb AppApp DevelopmentHTMLMySQLCSSJavaScript file 졸리운_곰 2016.06.07 808
48 Building websites in Python with Flask 졸리운_곰 2016.06.07 445
47 A minimal Flask-RESTful API looks like this 졸리운_곰 2016.06.07 520
46 Azure에서 Flask를 사용하여 웹앱 만들기 졸리운_곰 2016.06.07 702
45 Designing a RESTful API with Python and Flask 졸리운_곰 2016.06.07 485
44 Anonymous Web Scraping using Python and Tor file 졸리운_곰 2016.05.04 1284
43 Using TOR with Python file 졸리운_곰 2016.05.04 1911
42 Crawling anonymously with Tor in Python 졸리운_곰 2016.05.04 542
41 scrapy : 크롤링 해보기 file 졸리운_곰 2016.04.21 719
40 Python으로 xml 데이터를 mysql 데이터베이스 화 file 졸리운_곰 2016.03.13 780
39 Python으로 공공데이터 오픈 API 활용하기 졸리운_곰 2016.01.14 1225
38 Parse JSON using Python and store in MySQL file 졸리운_곰 2016.01.09 456
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED