python使用redis连接及TCP服务器和Flask框架

在pycharm的设置中project interpreter中安装redis
在windows本地启动redis服务器

使用redis连接

import redis
r = redis.Redis(host='127.0.0.1', port=6379, db=0, decode_responses=True)
r.set("number", "201814021024")
print(r.get("number"))

使用StrictRedis连接

import redis
r = redis.StrictRedis(host='127.0.0.1',port=6379,db=0,decode_responses=True)
pipe = r.pipeline()  #减少对服务器的请求数  #减少服务器客户端之间连接损耗
pipe.set('name','orange')
pipe.execute()
print(r.get('name'))

使用连接池

import redis
pool = redis.ConnectionPool(host='127.0.0.1',port=6379,db=0, decode_responses=True)
r = redis.Redis(connection_pool=pool)
print(r.get("name"))
r.hset("class","name","jack")
u = r.hget("class","name")
print(u)

TCP server

from socket import *
address = '127.0.0.1'    #监听哪些网络127.0.0.1是监听本机 0.0.0.0是监听整个网络
port = 12345
MAX = 1024
s = socket(AF_INET, SOCK_STREAM)
s.bind((address,port))
s.listen(128)
print("listening...")
flag = True
while True and flag:
    client, add = s.accept()
    print('connect from:',add)
    while True:
        data = client.recv(MAX).decode('utf-8')
        if data=='exit' or not data:
            flag = False
            break
        else:
            print(data)
    client.close()
s.close()

TCP client

from socket import *
address='127.0.0.1'
port=12345
s=socket(AF_INET, SOCK_STREAM)
s.connect((address,port))
while True:
    data=input('想要发送的数据:')
    if data=='exit':
        break
    s.send(data.encode())
s.close()

Flask

一个轻量级web框架

from socket import *
address='127.0.0.1'
port=12345
s=socket(AF_INET, SOCK_STREAM)
s.connect((address,port))
while True:
    data=input('想要发送的数据:')
    if data=='exit':
        break
    s.send(data.encode())
s.close()

Mysql


import pymysql  #导入模块
#1.建立连接
conn = pymysql.connect(
    host='localhost',
    user='root',
    database='yaojun',
    password='951225',
    port=3306
)
print(conn) #通过打印控制台来验证连接是否成功
cur = conn.cursor()
sql = "select * from lesson"  #mysql数据库内的table名
cur.execute(sql)
user = cur.fetchone()#获取一条数据
print(user)
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 酷酷鲨 设计师:CSDN官方博客 返回首页