我当时正在创建一个类似程序的小型聊天室,用户可以在其中注册,登录,发送和接收消息(在Pycharm中)。该程序在mysql数据库中包含用户详细信息,并在txt文件中聊天 我想在线托管它,以便可以由不同的用户在不同的计算机上访问它,所以我必须对我的代码进行哪些更改(当前设计为在单台计算机上工作)
import pymysql
import random
def register(firstName,lastName,password,userName,emailId):
db = pymysql.connect("localhost","root","pass","USERS")
cursor = db.cursor()
r=1
while(r!=0):
id = chr(random.randrange(65, 91)) + str(random.randrange(0, 10)) +str(random.randrange(0, 10))
r = cursor.execute("SELECT * FROM UserData WHERE ID = '{}';".format(id))
sql = "INSERT INTO UserData VALUES('{}','{}','{}','{}','{}','{}');".format(id,firstName,lastName,password,userName,emailId)
try:
cursor.execute(sql)
print("Registration successful")
file = open(id+'N.txt', 'a')
db.commit()
except Exception as e:
print("Registration unsuccessful")
print(str(e))
db.rollback()
db.close();
def displayNew(userId):
file = open(userId+'N.txt', 'r')
for message in file:
print(message)
open(userId+'N.txt', 'w').close()
def sendMessage(sender):
receiver = input("RECEIVER's USERNAME : ")
r = cursor.execute("SELECT * FROM UserData WHERE UserName = '{}';".format(receiver))
if (r == 1):
userInfo = cursor.fetchone()
if(sender>userInfo[0]):
chatfile = open(sender+'&'+userInfo[0]+'.txt', 'a')
elif(sender<userInfo[0]):
chatfile = open(userInfo[0]+'&'+sender+'.txt', 'a')
newfile=open(userInfo[0]+'N.txt', 'a')
message = input("MESSAGE(Single Line): ")
cursor.execute("SELECT * FROM UserData WHERE ID = '{}';".format(sender))
senderInfo = cursor.fetchone()
senderName = senderInfo[4]
chatfile.write(senderName+": "+message+"\n")
newfile.write(senderName+": "+message+"\n")
else:
print("USER DOES NOT EXIST")
retry=input("WANT TO RETRY(y/n)")
if(retry=="y"):
sendMessage(sender)
def oldMessage(receiver):
sender = input("SENDER's USERNAME : ")
r = cursor.execute("SELECT * FROM UserData WHERE UserName = '{}';".format(sender))
if (r == 1):
userInfo = cursor.fetchone()
if(receiver>userInfo[0]):
chatfile = open(receiver+'&'+userInfo[0]+'.txt', 'r')
elif(receiver<userInfo[0]):
chatfile = open(userInfo[0]+'&'+receiver+'.txt', 'r')
for message in chatfile:
print(message)
else:
print("USER DOES NOT EXIST")
retry=input("WANT TO RETRY(y/n)")
if(retry=="y"):
sendMessage(sender)
while(True):
db = pymysql.connect("localhost", "root", "dineshrashmi", "USERS")
cursor = db.cursor()
print("CHOICE 1: Login")
print("CHOICE 2: Register")
print("CHOICE 3: Exit")
ch = int(input("Enter Your Choice : "))
if(ch==1):
userName = input("User Name : ")
r=cursor.execute("SELECT * FROM UserData WHERE UserName = '{}';".format(userName))
if(r==1):
userInfo = cursor.fetchone()
password = input("Password : ")
if(userInfo[3]==password):
cursor.execute("SELECT * FROM UserData WHERE UserName = '{}';".format(userName))
print("WELCOME "+userInfo[1].upper()+" "+userInfo[2].upper())
displayNew(userInfo[0])
send=input("Do You Want To Send A Message(y/n) : ")
if(send=="y"):
sendMessage(userInfo[0])
view = input("Do You Want To View Old Message(y/n) : ")
if (view == "y"):
oldMessage(userInfo[0])
break
else:
print("INVALID PASSWORD")
else:
print("USER DOES NOT EXIST")
print("\n")
elif(ch==2):
confirmPass = False
userNameDuplicate = 1
emailDuplicate = 1
firstName = input("First Name : ")
lastName = input("Last Name : ")
while(userNameDuplicate!=0):
userName = input("User Name : ")
userNameDuplicate = int(cursor.execute("SELECT * FROM UserData WHERE UserName = '{}';".format(userName)))
if (userNameDuplicate != 0):
print("USER NAME ALREADY TAKEN")
print("Try Again!")
while(not confirmPass):
password = input("Password : ")
cpassword = input("Confirm Password : ")
if(password==cpassword):
confirmPass = True
else:
print("Password Mismatch")
print("Try Again!")
while (emailDuplicate != 0):
emailId = input("Email : ")
emailDuplicate = int(cursor.execute("SELECT * FROM UserData WHERE Email = '{}';".format(emailId)))
if (emailDuplicate != 0):
print("EMAIL ALREADY USED")
print("Try Again!")
regis = input("Register(y/n): ")
if(regis=="y"):
register(firstName,lastName,password,userName,emailId)
print("\n")
elif(ch==3):
break
else:
print("INVALID CHOICE")
print("\n")
db.close();
答案 0 :(得分:0)
从哪里开始?您可能会采用几种方法,但到目前为止,最常见的方法是使用基于HTML
,CSS
和JavaScript
的演示前端,并在服务器端提供一个用Python结束。
Web Server Gateway Interface
(WSGI)Python应用程序。如果没有,则必须按照Common Gateway Interface
(CGI)规范进行编程。form
,该页面将接受用户ID和密码并登录用户并在session
中维护登录信息。成功登录后,用户将被重定向到您的页面,该页面具有用于发送消息或查看旧消息的表格。locking
机制来序列化对文件的访问。我没有解释HTML
,CSS
,JavaScript
,WSGI
,CGI
等是什么,这会花费太长时间。这是供您调查。
答案 1 :(得分:0)
假设您托管一个MySql数据库,其IP为xxx.xxx.xx.xx
,并且具有一个用户(例如,root
,密码为PASS
)和一个数据库(例如,USERS
)。
使用PyMySQL,可以通过用代码中的IP替换'localhost'来连接到它。
示例:
...
db = pymysql.connect("xxx.xxx.xx.xx","root","pass","UERS")
cursor = db.cursor()
...
请确保已设置数据库实例,以使其可以在任何地方(*
,或者最好是从您想连接的地方)进行访问
您可以使用以下命令使用MySQL client验证连接:
mysql -h xxx.xxx.xx.xx -u root -pPASS
# To see the list of databases after getting connected
>show databases;