Compare commits

...

No commits in common. "main" and "python" have entirely different histories.
main ... python

45 changed files with 1033 additions and 6 deletions

View File

@ -0,0 +1 @@
print("hello")

View File

@ -0,0 +1 @@
print("test")

View File

@ -0,0 +1,3 @@
# Default ignored files
/shelf/
/workspace.xml

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.9 (03_pycharm_python_coursework_20240427)" project-jdk-type="Python SDK" />
</project>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/03_pycharm_python_coursework_20240427.iml" filepath="$PROJECT_DIR$/.idea/03_pycharm_python_coursework_20240427.iml" />
</modules>
</component>
</project>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>

View File

@ -0,0 +1,23 @@
from sklearn import tree
# 特征数据 身高 体重
# 1 - 有
# 0 - 无
features = [[178, 1], [155, 0], [180, 1]]
# 特征值
labels = ['male', 'female', 'male']
def decision_tree_classifier():
# 创建分类器
clf = tree.DecisionTreeClassifier()
# 模型训练
clf = clf.fit(features, labels)
# 预测
r1 = clf.predict([[158, 0]])
print('Data[158, 0] is label for: ', r1)
r2 = clf.predict([[190, 1]])
print('Data[190, 1] is label for: ', r2)
if __name__ == '__main__':
decision_tree_classifier()

View File

@ -0,0 +1,19 @@
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_node("输入层")
G.add_node("隐藏层 1")
G.add_node("隐藏层 2")
G.add_node("输出层")
G.add_edge("输入层", "隐藏层 1")
G.add_edge("输入层", "隐藏层 2")
G.add_edge("隐藏层 1", "输出层")
G.add_edge("隐藏层 2", "输出层")
pos = nx.spring_layout(G)
nx.draw_networkx(G, pos)
plt.rcParams['font.sans-serif']=['SimHei']
plt.show()

View File

@ -0,0 +1,24 @@
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_blobs
from sklearn import metrics
n_samples = 1500
x, y = make_blobs(n_samples=n_samples, centers=4, random_state=170)
x = StandardScaler().fit_transform(x)
KMeans = KMeans(n_clusters=4, n_init='auto', random_state=170)
KMeans.fit(x)
plt.figure(figsize=(12, 6))
plt.subplot(121)
plt.scatter(x[:, 0], x[:, 1], c='r')
plt.title("Before clustering")
plt.subplot(122)
plt.scatter(x[:, 0], x[:, 1], c=KMeans.labels_)
plt.title("After clustering")
plt.show()

View File

@ -0,0 +1,26 @@
import numpy as np
import matplotlib.pyplot as plt
# 转化矩阵
x = np.linspace(0, 10, 30).reshape(-1, 1)
# 斜率和截距 随机生成
w = np.random.randint(1, 5, 1)
b = np.random.randint(1, 10, 1)
# 根据一元一次方程计算目标值 y , 并加上 噪声, 数据上下有波动
y = x * w + b + np.random.randn(30, 1)
plt.scatter(x, y)
# 重构 x, b 截距
x = np.column_stack([x, np.full((30, 1), 1)])
# 正规方程求解
a = np.linalg.inv(x.T.dot(x)).dot(x.T).dot(y).round(2)
print(w, b)
print(a)
# 输出回归线性图
plt.plot(x[:, 0], x.dot(a), 'green')
plt.show()

View File

@ -0,0 +1,21 @@
import numpy as np
from sklearn.naive_bayes import BernoulliNB
x = np.array([[0, 1, 0, 1], [1, 1, 1, 1], [1, 1, 1, 0],
[0, 1, 1, 0], [0, 1, 0, 0], [0, 1, 0, 1],
[1, 1, 0, 1], [1, 0, 0, 1], [1, 1, 0, 1],
[0, 0, 0, 0]])
# 有风-潮湿-多云-闷热
y = np.array([1, 1, 1, 1, 0, 1, 0, 1, 1, 0])
bnb = BernoulliNB()
bnb.fit(x, y)
day_pre = [[1, 0, 1, 0]]
pre = bnb.predict(day_pre)
print("预测结果如下:\n", "*" * 50)
print("结果为: ", pre)
print("*" * 50)
# 进一步查看概率分析
pre_pro = bnb.predict_proba(day_pre)
print("不下雨的概率为: ", pre_pro[0][0], "\n下雨的概率为: ", pre_pro[0][1])

View File

@ -0,0 +1,45 @@
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn import datasets
# 载入红酒数据
wine = datasets.load_wine()
# 只选取前两个特征
x = wine.data[:, :2]
y = wine.target
# 拆分训练集和数据集
x_train, x_test, y_train, y_test = train_test_split(x, y)
forest = RandomForestClassifier(n_estimators=6, random_state=3)
# 拟合数据
forest.fit(x_train, y_train)
# 绘制图形
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])
x_min, x_max = x[:, 0].min() - 1, x[:, 0].max() + 1
y_min, y_max = x[:, 1].min() - 1, x[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, .02), np.arange(y_min, y_max, .02))
# 生成随机森林
z = forest.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx, yy, z, cmap=cmap_light)
# 绘制训练数据和测试数据的散点图
plt.scatter(x_train[:, 0], x_train[:, 1], c=y_train, cmap=cmap_bold, edgecolor='k', s=20)
plt.scatter(x_test[:, 0], x_test[:, 1], c=y_test, cmap=cmap_bold, edgecolor='k', s=50, marker='x')
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.title("Random Forest Classification")
plt.show()

View File

@ -0,0 +1,16 @@
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/

View File

@ -0,0 +1,13 @@
import numpy as np
import cv2
import matplotlib.pyplot as plt
# 读取图片
img = cv2.imread('source/data_01.png')
orb = cv2.ORB_create()
keypoints, descriptors = orb.detectAndCompute(img, None)
output_image = cv2.drawKeypoints(img, keypoints, None, color=(0, 255, 0), flags=0)
cv2.imshow('Feature KeyPoints', output_image)
cv2.waitKey(0)
cv2.destroyWindow()

View File

@ -0,0 +1,68 @@
import cv2
import matplotlib.pyplot as plt
import numpy as np
img = cv2.imread('source/data_02.jpg')
plt.subplot(3, 3, 1)
plt.imshow(img)
plt.axis('off')
plt.title('BGR')
# BGR -> RGB
img_RGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
plt.subplot(3, 3, 2)
plt.imshow(img_RGB)
plt.axis('off')
plt.title('RGB')
# 原图 -> 灰度
img_GRAY = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.subplot(3, 3, 3)
plt.imshow(img_GRAY)
plt.axis('off')
plt.title('GRAY')
# HSV
img_HSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
plt.subplot(3, 3, 4)
plt.imshow(img_HSV)
plt.axis('off')
plt.title('HSV')
# TCrCb
img_YcrCb = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)
plt.subplot(3, 3, 5)
plt.imshow(img_YcrCb)
plt.axis('off')
plt.title('YcrCb')
# HLS
img_HLS = cv2.cvtColor(img, cv2.COLOR_BGR2HLS)
plt.subplot(3, 3, 6)
plt.imshow(img_HLS)
plt.axis('off')
plt.title('HLS')
# XYZ
img_XYZ = cv2.cvtColor(img, cv2.COLOR_BGR2XYZ)
plt.subplot(3, 3, 7)
plt.imshow(img_XYZ)
plt.axis('off')
plt.title('XYZ')
# LAB
img_LAB = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
plt.subplot(3, 3, 8)
plt.imshow(img_LAB)
plt.axis('off')
plt.title('LAB')
# YUV
img_YUV = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
plt.subplot(3, 3, 9)
plt.imshow(img_YUV)
plt.axis('off')
plt.title('LAB')
plt.show()

View File

@ -0,0 +1,22 @@
import cv2
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
img_1 = cv2.imread('source/data_03.jpg')
cv2.imshow("img1", img_1)
img_2 = np.zeros(img_1.shape, dtype=np.uint8)
img_2[200:400, 200:400] = 255
cv2.imshow("img2", img_2)
result_or = cv2.bitwise_or(img_1, img_2)
result_and = cv2.bitwise_and(img_1, img_2)
result_not = cv2.bitwise_not(img_1, img_2)
result_xor = cv2.bitwise_xor(img_1, img_2)
cv2.imshow("or", result_or)
cv2.imshow("and", result_and)
cv2.imshow("not", result_not)
cv2.imshow("xor", result_xor)
cv2.waitKey()
cv2.destroyWindow()

View File

@ -0,0 +1,17 @@
import cv2
img = cv2.imread("source/data_02.jpg")
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gray, scaleFactor=1.09, minNeighbors=3, minSize=(5, 5))
print(faces)
print("该图一共有{0}人脸".format(len(faces)))
for(x, y, w, h) in faces:
cv2.circle(img, (int((2 * x + w) / 2), int((2 * y + h) / 2)),
int(w / 2), (0, 255, 0), 2)
cv2.imshow("result", img)
cv2.waitKey()
cv2.destroyWindow()

View File

@ -0,0 +1,20 @@
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.datasets import load_iris
# 加载数据
iris = load_iris()
x = iris.data
# 执行 PCA
pca = PCA(n_components=2)
x_reduced = pca.fit_transform(x)
# 绘制结果
plt.figure(figsize=(10, 5))
plt.scatter(x_reduced[:, 0], x_reduced[:, 1], c=iris.target)
plt.xlabel('First Principal Component')
plt.ylabel('Second Principal Component')
plt.title('PCA of Iris Dataset')
plt.show()

Binary file not shown.

After

Width:  |  Height:  |  Size: 482 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 232 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

View File

@ -0,0 +1,3 @@
# 默认忽略的文件
/shelf/
/workspace.xml

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="jdk" jdkName="Python 3.9 (Python_Venv) (2)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.9 (Python_Venv) (2)" project-jdk-type="Python SDK" />
</project>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/Python_pyqt_MainLearn.iml" filepath="$PROJECT_DIR$/.idea/Python_pyqt_MainLearn.iml" />
</modules>
</component>
</project>

View File

@ -0,0 +1,162 @@
import sys
import time
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
class MyWindow(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("信号与槽")
self.init_ui()
# 主初始化方法
def main_window_init(self):
# 设置窗口大小
self.resize(300, 200)
# 主界面布局 [垂直布局]
self.main_layout = QVBoxLayout()
def init_ui(self):
self.main_window_init()
# 信息Box初始化
self.message_widget_init()
# 设置Box初始化
self.seeting_widget_init()
# 将两个Group添加至主布局器中
self.main_layout.addWidget(self.message_group_box)
self.main_layout.addWidget(self.seeting_group_box)
self.setLayout(self.main_layout)
# 信息部分初始化方法
def message_widget_init(self):
# 信息界面组Group
self.message_group_box = QGroupBox("信息")
# 两个控件水平布局
horizon_layout = QHBoxLayout()
# 控件1设置转盘控件
self.control_1 = QDial()
# 是否循环滚动 [默认是]
self.control_1.setWrapping(True)
# 是否显示刻度
self.control_1.setNotchesVisible(True)
# 绑定信号至槽函数Dialg_Signal
self.control_1.valueChanged.connect(self.Dialg_Signal)
# 控件2信息框
# 信息框垂直布局
message_vertical_layout = QVBoxLayout()
# 文字
Message_Lable = QLabel("数值")
# 信息框
self.control_2 = QSpinBox()
# 两个控件添加至垂直布局中
message_vertical_layout.addWidget(self.control_2)
message_vertical_layout.addWidget(Message_Lable)
# 两个控件绑定至垂直布局中
horizon_layout.addWidget(self.control_1)
horizon_layout.addLayout(message_vertical_layout)
# 将垂直布局添加至组中
self.message_group_box.setLayout(horizon_layout)
# 设置部分初始化方法
def seeting_widget_init(self):
# 设置界面组Group
self.seeting_group_box = QGroupBox("设置")
# 控件网格布局
self.grid_layout = QGridLayout()
# 设置项:是否显示刻度
self.seeting_norchesvisible()
self.seeting_notchesVisile()
# 显示刻度组添加至网格布局中
self.grid_layout.addWidget(self.norchesvisible_group_box,1,1)
# 是否循环组添加至网格布局中
self.grid_layout.addWidget(self.notchesVisile_group_box,1,2)
# 将网格布局添加至主Group中
self.seeting_group_box.setLayout(self.grid_layout)
# 设置项:是否显示刻度
def seeting_norchesvisible(self):
# 显示刻度组Group
self.norchesvisible_group_box = QGroupBox("显示刻度")
# 下拉选框控件[是否显示刻度]
self.Combo_NotchesVisible = QComboBox()
# 该Group中为垂直布局
norchesvisible_vertical_layout = QVBoxLayout()
# 配置下拉选框是否可以编辑
self.Combo_NotchesVisible.setEditable(False)
# 添加控件元素
self.Combo_NotchesVisible.addItem("显示")
self.Combo_NotchesVisible.addItem("不显示")
# 连接槽函数至seeting_norchesvisible_Signal
self.Combo_NotchesVisible.currentIndexChanged.connect(self.seeting_norchesvisible_Signal)
# 将Combo_NotchesVisible[下拉选择框]添加至垂直布局中
norchesvisible_vertical_layout.addWidget(self.Combo_NotchesVisible)
# 将norchesvisible_vertical_layout[Group]添加至主Group中
self.norchesvisible_group_box.setLayout(norchesvisible_vertical_layout)
# 设置项:是否允许转盘循环
def seeting_notchesVisile(self):
# 是否循环Group
self.notchesVisile_group_box = QGroupBox("循环滚动")
# 下拉框选择控件
self.Combo_notchesVisile = QComboBox()
# 该Group内为垂直布局
notchesVisile_vertical_layout = QVBoxLayout()
# 配置下拉选框是否可以编辑
self.Combo_NotchesVisible.setEditable(False)
# 添加控件元素
self.Combo_notchesVisile.addItem("循环")
self.Combo_notchesVisile.addItem("不循环")
# 连接槽函数至
self.Combo_notchesVisile.currentIndexChanged.connect(self.seeting_notchesVisile_Signal)
# 将Combo_notchesVisile[下拉选择框]添加至垂直布局中
notchesVisile_vertical_layout.addWidget(self.Combo_notchesVisile)
# 将notchesVisile_vertical_layout[Group]添加至主Group中
self.notchesVisile_group_box.setLayout(notchesVisile_vertical_layout)
# 转盘信号槽方法 [回调函数]
def Dialg_Signal(self):
self.control_2.setValue(self.control_1.value())
# 设置项:是否显示刻度 [回调函数]
def seeting_norchesvisible_Signal(self):
# 判断索引号0[显示] 1[不显示]
if self.Combo_NotchesVisible.currentIndex() == 0:
self.control_1.setNotchesVisible(True)
elif self.Combo_NotchesVisible.currentIndex() == 1:
self.control_1.setNotchesVisible(False)
# 设置项:是否允许转盘循环 [回调函数]
def seeting_notchesVisile_Signal(self):
# 判断索引号0[循环] 1[不循环]
if self.Combo_notchesVisile.currentIndex() == 0:
self.control_1.setWrapping(True)
elif self.Combo_notchesVisile.currentIndex() == 1:
self.control_1.setWrapping(False)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MyWindow()
w.show()
app.exec()

3
05_pycharm_python_pyqt5学习/.idea/.gitignore generated vendored Normal file
View File

@ -0,0 +1,3 @@
# 默认忽略的文件
/shelf/
/workspace.xml

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="jdk" jdkName="Python 3.9 (Python_Venv) (3)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@ -0,0 +1,12 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyUnresolvedReferencesInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredIdentifiers">
<list>
<option value="PyQt5.QtCore.Qt.AlignTop" />
</list>
</option>
</inspection_tool>
</profile>
</component>

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.9 (Python_Venv) (3)" project-jdk-type="Python SDK" />
</project>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/002_Python_pyqt5_学习.iml" filepath="$PROJECT_DIR$/.idea/002_Python_pyqt5_学习.iml" />
</modules>
</component>
</project>

View File

@ -0,0 +1,106 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>467</width>
<height>145</height>
</rect>
</property>
<property name="windowTitle">
<string>登录器</string>
</property>
<widget class="QLabel" name="UserID_Label">
<property name="geometry">
<rect>
<x>10</x>
<y>30</y>
<width>61</width>
<height>21</height>
</rect>
</property>
<property name="font">
<font>
<family>Adobe 黑体 Std R</family>
<pointsize>12</pointsize>
</font>
</property>
<property name="text">
<string>用户ID</string>
</property>
</widget>
<widget class="QLineEdit" name="UserID_Edit">
<property name="geometry">
<rect>
<x>80</x>
<y>30</y>
<width>161</width>
<height>20</height>
</rect>
</property>
</widget>
<widget class="QLineEdit" name="UserPwd_Edit">
<property name="geometry">
<rect>
<x>80</x>
<y>60</y>
<width>161</width>
<height>20</height>
</rect>
</property>
</widget>
<widget class="QLabel" name="UserPwd_Label">
<property name="geometry">
<rect>
<x>10</x>
<y>60</y>
<width>61</width>
<height>21</height>
</rect>
</property>
<property name="font">
<font>
<family>Adobe 黑体 Std R</family>
<pointsize>12</pointsize>
</font>
</property>
<property name="text">
<string>密码:</string>
</property>
</widget>
<widget class="QPushButton" name="BTN_Login">
<property name="geometry">
<rect>
<x>190</x>
<y>90</y>
<width>51</width>
<height>21</height>
</rect>
</property>
<property name="font">
<font>
<family>Adobe 黑体 Std R</family>
<pointsize>12</pointsize>
</font>
</property>
<property name="text">
<string>登录</string>
</property>
</widget>
<widget class="QTextBrowser" name="Message_Text">
<property name="geometry">
<rect>
<x>250</x>
<y>20</y>
<width>201</width>
<height>111</height>
</rect>
</property>
</widget>
</widget>
<resources/>
<connections/>
</ui>

View File

@ -0,0 +1,94 @@
import json
import sys
import time
import requests
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import *
from PyQt5 import uic,QtCore
class LoginThread (QThread):
# 创建自定义信号
Start_Login_Signal = pyqtSignal(str)
def __init__(self, signal):
super().__init__()
self.Login_Complete_Signal = signal
def Login_by_Requests(self, User_Password_Json):
User_Data_Json = json.loads(User_Password_Json)
print(User_Data_Json.get("User_ID"))
print(User_Data_Json.get("User_Password"))
# 使用Requests模块发送请求 POST
r = requests.post(url="https://service-r80raze1-1300421481.sh.apigw.tencentcs.com/release/Python_Pyqt_Learn", json=User_Data_Json)
print("接受服务器响应:", r.content.decode())
ret = r.json()
print("发送信号给UI线程")
self.Login_Complete_Signal.emit(json.dumps(ret))
def run(self):
while True:
print ("子线程 running...")
time.sleep(1)
class UserMainWindow(QWidget):
Login_Status_Signal = pyqtSignal(str)
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
self.ui = uic.loadUi("./UserWindow.ui")
# 提取要操作的控件
self.Get_Widget()
# 绑定登录按钮至槽函数User_Login
self.BTN_Login.clicked.connect(self.User_Login)
# 子线程登录成功后向主线程发送信号
self.Login_Status_Signal.connect(self.Login_Status)
# 创建子线程
self.Login_Thread = LoginThread(self.Login_Status_Signal)
# 将要创建的子线程类中的信号进行绑定
self.Login_Thread.Start_Login_Signal.connect(self.Login_Thread.Login_by_Requests)
# 子线程开始工作
self.Login_Thread.start()
def Get_Widget(self):
# 用户信息输入框
# 用户ID
self.UserInputID_Edit = self.ui.UserID_Edit
# 用户密码
self.UserInputPwd_Edit = self.ui.UserPwd_Edit
# 信息输出框
self.MessageOutput_Text = self.ui.Message_Text
# 按钮:用户登录
self.BTN_Login = self.ui.BTN_Login
def User_Login(self):
# 获取用户输入文本
User_ID = self.UserInputID_Edit.text()
User_Password = self.UserInputPwd_Edit.text()
# 发送信号,子线程开始登录
self.Login_Thread.Start_Login_Signal.emit(json.dumps({"User_ID": User_ID, "User_Password": User_Password}))
def Login_Status(self, status):
Status_Dict = json.loads(status)
print(Status_Dict.get("errmsg"))
self.MessageOutput_Text.setText(Status_Dict.get("errmsg"))
self.MessageOutput_Text.repaint()
if __name__ == '__main__':
QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
app = QApplication(sys.argv)
w = UserMainWindow()
# 展示窗口
w.ui.show()
app.exec()

3
06_pycharm_python_阿里云Api_DDNS/.idea/.gitignore generated vendored Normal file
View File

@ -0,0 +1,3 @@
# 默认忽略的文件
/shelf/
/workspace.xml

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="jdk" jdkName="Python 3.10" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@ -0,0 +1,56 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredPackages">
<value>
<list size="27">
<item index="0" class="java.lang.String" itemvalue="pathspec" />
<item index="1" class="java.lang.String" itemvalue="Babel" />
<item index="2" class="java.lang.String" itemvalue="mkdocs-material" />
<item index="3" class="java.lang.String" itemvalue="PyYAML" />
<item index="4" class="java.lang.String" itemvalue="python-dateutil" />
<item index="5" class="java.lang.String" itemvalue="paginate" />
<item index="6" class="java.lang.String" itemvalue="mkdocs" />
<item index="7" class="java.lang.String" itemvalue="MarkupSafe" />
<item index="8" class="java.lang.String" itemvalue="importlib-metadata" />
<item index="9" class="java.lang.String" itemvalue="Jinja2" />
<item index="10" class="java.lang.String" itemvalue="zipp" />
<item index="11" class="java.lang.String" itemvalue="Markdown" />
<item index="12" class="java.lang.String" itemvalue="pygments" />
<item index="13" class="java.lang.String" itemvalue="six" />
<item index="14" class="java.lang.String" itemvalue="mergedeep" />
<item index="15" class="java.lang.String" itemvalue="packaging" />
<item index="16" class="java.lang.String" itemvalue="mkdocs-glightbox" />
<item index="17" class="java.lang.String" itemvalue="click" />
<item index="18" class="java.lang.String" itemvalue="mkdocs-material-extensions" />
<item index="19" class="java.lang.String" itemvalue="pyyaml-env-tag" />
<item index="20" class="java.lang.String" itemvalue="regex" />
<item index="21" class="java.lang.String" itemvalue="watchdog" />
<item index="22" class="java.lang.String" itemvalue="ghp-import" />
<item index="23" class="java.lang.String" itemvalue="material" />
<item index="24" class="java.lang.String" itemvalue="platformdirs" />
<item index="25" class="java.lang.String" itemvalue="pymdown-extensions" />
<item index="26" class="java.lang.String" itemvalue="colorama" />
</list>
</value>
</option>
</inspection_tool>
<inspection_tool class="PyPep8NamingInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
<option name="ignoredErrors">
<list>
<option value="N802" />
<option value="N803" />
<option value="N806" />
</list>
</option>
</inspection_tool>
<inspection_tool class="PyUnresolvedReferencesInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredIdentifiers">
<list>
<option value="PyQt5.QtCore.Qt.AlignTop" />
</list>
</option>
</inspection_tool>
</profile>
</component>

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.10" project-jdk-type="Python SDK" />
</project>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/004_Python_Requist.iml" filepath="$PROJECT_DIR$/.idea/004_Python_Requist.iml" />
</modules>
</component>
</project>

View File

@ -0,0 +1,152 @@
#!/usr/bin/env python
#coding=utf-8
# 加载核心SDK
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
# 加载获取 、 新增、 更新、 删除接口
from aliyunsdkalidns.request.v20150109 import DescribeSubDomainRecordsRequest, AddDomainRecordRequest, UpdateDomainRecordRequest, DeleteDomainRecordRequest
# 加载内置模块
import json,urllib
# AccessKey 和 Secret 建议使用 RAM 子账户的 KEY 和 SECRET 增加安全性
ID = 'xxxxxxx'
SECRET = 'xxxxxx'
# 地区节点 可选地区取决于你的阿里云帐号等级普通用户只有四个分别是杭州、上海、深圳、河北具体参考官网API
regionId = 'cn-hangzhou'
# 配置认证信息
client = AcsClient(ID, SECRET, regionId)
# 设置主域名
DomainName = 'binghe.com'
# 子域名列表 列表参数可根据实际需求增加或减少值
SubDomainList = ['a', 'b', 'c']
# 获取外网IP 三个地址返回的ip地址格式各不相同3322 的是最纯净的格式, 备选1为 json格式 备选2 为curl方式获取 两个备选地址都需要对获取值作进一步处理才能使用
def getIp():
# 备选地址1 http://pv.sohu.com/cityjson?ie=utf-8 2curl -L tool.lu/ip
with urllib.request.urlopen('http://www.3322.org/dyndns/getip') as response:
html = response.read()
ip = str(html, encoding='utf-8').replace("\n", "")
return ip
# 查询记录
def getDomainInfo(SubDomain):
request = DescribeSubDomainRecordsRequest.DescribeSubDomainRecordsRequest()
request.set_accept_format('json')
# 设置要查询的记录类型为 A记录 官网支持A / CNAME / MX / AAAA / TXT / NS / SRV / CAA / URL隐性显性转发 如果有需要可将该值配置为参数传入
request.set_Type("A")
# 指定查记的域名 格式为 'test.binghe.com'
request.set_SubDomain(SubDomain)
response = client.do_action_with_exception(request)
response = str(response, encoding='utf-8')
# 将获取到的记录转换成json对象并返回
return json.loads(response)
# 新增记录 (默认都设置为A记录通过配置set_Type可设置为其他记录)
def addDomainRecord(client,value,rr,domainname):
request = AddDomainRecordRequest.AddDomainRecordRequest()
request.set_accept_format('json')
# request.set_Priority('1') # MX 记录时的必选参数
request.set_TTL('600') # 可选值的范围取决于你的阿里云账户等级,免费版为 600 - 86400 单位为秒
request.set_Value(value) # 新增的 ip 地址
request.set_Type('A') # 记录类型
request.set_RR(rr) # 子域名名称
request.set_DomainName(domainname) #主域名
# 获取记录信息,返回信息中包含 TotalCount 字段,表示获取到的记录条数 0 表示没有记录, 其他数字为多少表示有多少条相同记录正常有记录的值应该为1如果值大于1则应该检查是不是重复添加了相同的记录
response = client.do_action_with_exception(request)
response = str(response, encoding='utf-8')
relsult = json.loads(response)
return relsult
# 更新记录
def updateDomainRecord(client,value,rr,record_id):
request = UpdateDomainRecordRequest.UpdateDomainRecordRequest()
request.set_accept_format('json')
# request.set_Priority('1')
request.set_TTL('600')
request.set_Value(value) # 新的ip地址
request.set_Type('A')
request.set_RR(rr)
request.set_RecordId(record_id) # 更新记录需要指定 record_id ,该字段为记录的唯一标识,可以在获取方法的返回信息中得到该字段的值
response = client.do_action_with_exception(request)
response = str(response, encoding='utf-8')
return response
# 删除记录
def delDomainRecord(client,subdomain):
info = getDomainInfo(subdomain)
if info['TotalCount'] == 0:
print('没有相关的记录信息,删除失败!')
elif info["TotalCount"] == 1:
print('准备删除记录')
request = DeleteDomainRecordRequest.DeleteDomainRecordRequest()
request.set_accept_format('json')
record_id = info["DomainRecords"]["Record"][0]["RecordId"]
request.set_RecordId(record_id) # 删除记录需要指定 record_id ,该字段为记录的唯一标识,可以在获取方法的返回信息中得到该字段的值
result = client.do_action_with_exception(request)
print('删除成功,返回信息:')
print(result)
else:
# 正常不应该有多条相同的记录,如果存在这种情况,应该手动去网站检查核实是否有操作失误
print("存在多个相同子域名解析记录值,请核查后再操作!")
# 有记录则更新,没有记录则新增
def setDomainRecord(client,value,rr,domainname):
info = getDomainInfo(rr + '.' + domainname)
if info['TotalCount'] == 0:
print('准备添加新记录')
add_result = addDomainRecord(client,value,rr,domainname)
print(add_result)
elif info["TotalCount"] == 1:
print('准备更新已有记录')
record_id = info["DomainRecords"]["Record"][0]["RecordId"]
cur_ip = getIp()
old_ip = info["DomainRecords"]["Record"][0]["Value"]
if cur_ip == old_ip:
print ("新ip与原ip相同不更新")
else:
update_result = updateDomainRecord(client,value,rr,record_id)
print('更新成功,返回信息:')
print(update_result)
else:
# 正常不应该有多条相同的记录,如果存在这种情况,应该手动去网站检查核实是否有操作失误
print("存在多个相同子域名解析记录值,请核查删除后再操作!")
IP = getIp()
# 循环子域名列表进行批量操作
for x in SubDomainList:
setDomainRecord(client,IP,x,DomainName)
# 删除记录测试
# delDomainRecord(client,'b.jsoner.com')
# 新增或更新记录测试
# setDomainRecord(client,'192.168.3.222','a',DomainName)
# 获取记录测试
# print (getDomainInfo(DomainName, 'y'))
# 批量获取记录测试
# for x in SubDomainList:
# print (getDomainInfo(DomainName, x))
# 获取外网ip地址测试
# print ('(' + getIp() + ')')

View File

@ -1,8 +1,9 @@
# 代码托管 # Python 代码
## 包含语言 ## 项目命名规范
- Cplus * 序号
- Java * IDE
- Python * 语言
- Golang * 项目简述
* 创建时间