localhost:8000是指本地主機的8000埠。這個埠通常用於Web伺服器,默認情況下,只要運行了Web伺服器並監聽了8000埠,訪問http://localhost:8000就能夠看到Web伺服器的默認頁面。在這篇文章中,我們將從多個方面介紹localhost:8000,並展示如何使用它進行開發。
一、localhost:8000的基本概念
1、默認Web伺服器
<!DOCTYPE html>
<html>
<body>
<h1>這是一個簡單的Web伺服器</h1>
<p>歡迎來到localhost:8000!</p>
</body>
</html>
2、localhost的作用
3、埠號的作用
二、localhost:8000的使用方法
1、靜態網頁的展示
python -m http.server 8000
2、動態網頁的處理
3、測試介面的使用
三、localhost:8000的開發應用
1、伺服器和客戶端之間的連接
// 客戶端
const url = "http://localhost:8000/api/data";
fetch(url)
.then(response => response.json()) // 轉換為JSON
.then(data => console.log(data))
2、資料庫的連接
import pymysql.cursors
# 連接資料庫
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
# 執行SQL語句並提交
try:
with connection.cursor() as cursor:
# 創建一條記錄
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('test@test.com', 'test123'))
# 提交
connection.commit()
finally:
# 關閉連接
connection.close()
3、REST API的實現
from flask import Blueprint, jsonify, request
api = Blueprint('api', __name__, url_prefix='/api')
# REST API路由定義
@api.route('/data', methods=['GET'])
def get_data():
data = {'message': 'Hello, World!'}
return jsonify(data)
四、小結
在本篇文章中,我們對localhost:8000進行了多方面的介紹,並展示了它的使用方法和開發應用。藉助localhost:8000,我們可以輕鬆地展示網頁、處理動態網頁、測試介面、連接資料庫以及實現REST API。在日常的開發工作中,熟練掌握localhost:8000的使用將會是非常有用的。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/239964.html