Khi nói tới lập trình website thì có lẽ rằng cực kỳ nhiều lập trình viên sẽ liên tưởng ngay tới ngôn từ php. Ngôn ngữ php được biết đến là ngôn từ được tạo ra để ship hàng cho việc làm web với rất nhiều framework, cms có thêm với một hội đồng rất đông, hung hãn nhưng tại bài viết tôi mong ước trình diễn một đến gần hơn khác, bằng ngôn từ khác cho công cuộc làm web đấy là lập trình web với ngôn từ python .
Tóm Tắt
I. Tạo môi trường
Chọn lựa framework: Hiện tại có rất nhiều framework hỗ trợ lập trình website bằng ngôn ngữ python trong đó có 3 cái tên đó là Django, Flask, Pyramid … Mỗi framework đều có điểm mạnh và điểm yếu riêng của nó, để hiểu cụ thể hơn hãy tham khảo phần “Link tham khảo” ở phần cuối của bài viết này. tại chẳng hạn như này tôi recommend về framework Flask (Flask là một microframework cho Python dựa trên Werkzeug, Jinja 2.)
Thiết lập framework Flask:
Thiết lập python và pid như link sau:
Bạn đang đọc: Hướng dẫn Cách lập trình Web với Python hiệu quả mới nhất 2020 – https://final-blade.com
https://docs.python-guide.org/starting/install3/osx/
Cài đặt Flask
pip install flask
Tạo thư mục của dự án Bất Động Sản :
mkdir hoctiengnhatonline
Tạo một tệp khởi tạo app.py trong thư mục “ hoctiengnhatonline ”, sau đó thông số kỹ thuật để sử dụng module Flask tại tệp app.py
from flask import Flask
app = Flask(__name__)@app.route("/")defmain():return"Welcome"if __name__ == "__main__":
app.run()
Thực thi app.py
python app.py
Vào trình duyệt và truy xuất đường link dưới đây
http://localhost:5000/
II. Xây dựng trang chủ
Tại folder hoctiengnhatonline
tạo folder templates
, tại thư mục templates
xây dựng một tệp đặt tên là index.html
, mở tệp index.html
thêm đoạn code HTML sau đây vào:
Hoc Tieng Nhat trực tuyến Apptitle>
<đường linkhref="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"rel="stylesheet">
head>
Mở app.py
, import render_template
, cái mà chúng ta sẽ sử dụng để kết xuất những tập tin template
.
from flask import Flask, render_template
Sửa phương pháp chủ yếu để trả về tập tin template đã được kết xuất .
defmain():return render_template('index.html')
Mở trình duyệt, truy vấn http://localhost:5000/, sẽ thấy màn hình hiển thị dưới đây :
>> > Blog san sẻ kỹ năng và kiến thức kiến thiết xây dựng website
III. Xây dựng trang đăng ký
Bước 1: xây dựng Database
Tạo database tên là hoctiengnhatonline
CREATEDATABASE hoctiengnhatonline;
xây dựng bảng lưu người sử dụng tbl_user
CREATETABLE`hoctiengnhatonline`.`tbl_user` (`user_id`BIGINT AUTO_INCREMENT,`user_name`VARCHAR(4 .) NULLvà`user_username`VARCHAR(4) NULLvà`user_password`VARCHAR(4) NULL,
PRIMARY KEY (`user_id`));
tạo thủ tục để lưu nội dung người dùng đặt tên là sp_createUser
DELIMITER $CREATE DEFINER=`root`@`localhost`PROCEDURE`sp_createUser`(IN p_name VARCHAR(2),IN p_username VARCHAR(2 .),IN p_password VARCHAR(2)
)BEGINif ( selectexists (select1from tbl_user where user_username = p_username) ) THENselect'Username Exists !!';
ELSEinsertinto tbl_user
(
user_name,
user_username,
user_password
)values(
p_name,
p_username,
p_password
);ENDIF;END$
DELIMITER ;
Bước 2. Tạo bố cụ và giao diện đăng ký
Trong folder hoctiengnhatonline/templates
xây dựng một tệp HTML đặt tên là signup.html
, sau đó chèn đoạn code phía dưới vào tập tin signup.html
Hoc Tieng Nhat trực tuyến Apptitle>
head>
Tạo thêm tệp CSS
trong folder static
bên trong hoctiengnhatonline
body padding-top : 40 px ; padding-bottom : 40 px ;.form-signin max-width : 330 px ; padding : 15 px ; margin : 0 auto ;.form-signin.form-signin-headingvà.form-signin.checkbox margin-bottom : 10 px ;.form-signin.checkbox font-weight : normal ;.form-signin.form-control position : relative ; height : auto ; - webkit-box-sizing : border-box ; - moz-box-sizing : border-box ; box-sizing : border-box ; padding : 10 px ; font-size : 16 px ;.form-signin.form-control:focus z-index : 2 ;.form-signininput[type="email"] margin-bottom : - 1 px ; border-bottom-right-radius : 0 ; border-bottom-left-radius : 0 ;.form-signininput[type="password"] margin-bottom : 10 px ; border-top-left-radius : 0 ; border-top-right-radius : 0 ;
Thêm đoạn code sau vào trong file app.py
@app.route('/showSignUp')defshowSignUp():return render_template('signup.html')
Nhập chuột vào nút SignUp
màn hình ảnh dưới đây được hiển thị:
Bước 3 Xây dựng phương thức đăng ký
Thêm đoạn code giải quyết đăng ký signUp
và import thêm thư viện vào tệp app.py
@app.route('/signUp',methods=['POST'])defsignUp():# read the posted values from the UI_name = request.form['inputName']
_email = request.form['inputEmail']
_password = request.form['inputPassword']# validate the received valuesif _name and _email and_password:return json.dumps(' html ' : ' All fields good ! ! ')else:return json.dumps(' html ' : ' Enter the required fields ')
,
from flask import Flask, render_template, json, request
Bước 4 Tạo đăng ký từ client
$(function() USD ( ' # btnSignUp ' ). click ( function ( ) USD. ajax ( url : ' / signUp ', data : USD ( ' form ' ). serialize ( ), type : ' POST'vàsuccess : function ( response ) console.log ( response ) ;, error : function ( error ) console.log ( error ) ; ) ; ) ;);
Bước 5. Lưu thông tin bằng thủ tục của Mysql
đầu tiên cài đặt thư viện mysql
cho flask bằng lệnh sau:
pip install flask-mysql
trong file app.py
import thêm thư viện , thêm các đoạn code giải quyết sau vào
from flask import Flask, render_template, json, requestfrom flaskext.mysql import MySQLfrom werkzeug import generate_password_hash, check_password_hash
mysql = MySQL()
app = Flask(__name__)# MySQL configurationsapp.config['MYSQL_DATABASE_USER'] = 'root'app.config['MYSQL_DATABASE_PASSWORD'] = '12345678'app.config['MYSQL_DATABASE_DB'] = 'hoctiengnhatonline'app.config['MYSQL_DATABASE_HOST'] = 'localhost'mysql.init_app(app)
Tại function xử lý ĐK thông tin người dùng thêm đoạn code sau :
# validate the received valuesif _name and _email and _password:# All Good, let's call MySQLconn = mysql.connect()
cursor = conn.cursor()
_hashed_password = generate_password_hash(_password)
cursor.callproc('sp_createUser',(_name,_email,_hashed_password))
data = cursor.fetchall()if len(data) is0:
conn.commit()return json.dumps(' message ' : ' User created successfully ! ')else:return json.dumps(' error ' : str ( data [ 0 ] ))else:return json.dumps(' html ' : ' Enter the required fields ')except Exception as e:return json.dumps(' error ' : str ( e ))finally:
cursor.close()
conn.close()
Lưu những thay đổi và khởi động lại máy chủ. Đi đến trang đăng ký và nhập name
, email
và mật khẩu
, nhấp vào nút Sign Up
. Khi xây dựng chiến thắng người sử dụng, bạn sẽ có khả năng thấy một thông báo trong bố cụ và giao diện console của trình duyệt.
" message " : " User created successfully ! "
VI. Tổng kết
Trong bài đăng này, tôi trình diễn tuyệt kỹ cơ bản nhất khi lập trình website bằng ngôn từ python dùng framework Flask mong rằng sẽ phần nào giúp ích được phần nào đó cho bạn đọc lần đầu lập trình web bằng ngôn từ python. Hãy tìm hiểu thêm toàn bộ source code ở link tìm hiểu thêm dưới đây. trong bài đăng sau đó tôi sẽ thuyết trình kỹ hơn về những quan tâm khi lập trình website bằng python .
Xem thêm: Business Intelligence là gì? Các thuật ngữ thông dụng mà doanh nghiệp đang dùng
Xem thêm: HTML Là Gì, Giới Thiệu Về HTML
>> >> Blog san sẻ kỹ năng và kiến thức thiết kế xây dựng website
V. Đường link tìm đọc
Học lập Trình
Nguồn : https://blog.vietnamlab.vn/
Source: https://final-blade.com
Category: Kiến thức Internet