- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我从我之前的问题开始继续我的 python 游戏
Socket issue when using threads
我遇到了另一个问题,这次是关于 MySQL,它与我在 Pythonanywhere.com 上的托管服务器并存。错误如下:
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/mysql/connector/network.py", line 191, in recv_plain
chunk = self.sock.recv(1)
InterruptedError: [Errno 4] Interrupted system call
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python3.4/dist-packages/flask/_compat.py", line 33, in reraise
raise value
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.4/dist-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/elvishknight1/mysite/flask_app.py", line 81, in intro
c.execute("SELECT * FROM players WHERE name=%s", (ID,))
File "/usr/local/lib/python3.4/dist-packages/mysql/connector/cursor.py", line 515, in execute
self._handle_result(self._connection.cmd_query(stmt))
File "/usr/local/lib/python3.4/dist-packages/mysql/connector/connection.py", line 684, in cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "/usr/local/lib/python3.4/dist-packages/mysql/connector/connection.py", line 476, in _send_cmd
return self._socket.recv()
File "/usr/local/lib/python3.4/dist-packages/mysql/connector/network.py", line 212, in recv_plain
errno=2055, values=(self.get_address(), _strioerror(err)))
mysql.connector.errors.OperationalError: 2055: Lost connection to MySQL server at 'mysql.server:3306', system error: 4 Interrupted system call
2014-12-18 16:27:13,712 :Exception on /chat/ [GET]
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/mysql/connector/network.py", line 189, in recv_plain
packet = self.sock.recv(1)
InterruptedError: [Errno 4] Interrupted system call
随着服务器发出更多的 get 请求,上面的重复内容覆盖了错误日志
这是主要的应用程序代码(如果不是最pythonic的,请见谅)
from flask import Flask, render_template, request, jsonify
import mysql.connector
from grid import Grid
from game import Game
import random
from monster import Monster
from descriptions import Descriptions
from calculator import Calculator
app = Flask(__name__)
sql = mysql.connector.connect(user="elvishknight1", password="351797asd", host="mysql.server", database="elvishknight1$Overseer", buffered=True)
c = sql.cursor()
game=Game()
grid=Grid()
monsters = []
x=0
y=0
descriptions=Descriptions()
calculator = Calculator()
@app.route('/')
def index():
return render_template("intro.html",)
@app.route('/mod/351797Aa')
def moderator():
return render_template("moderate.html",)
@app.route('/mod/')
def worldMaker():
grid.makeGrid()
for x in range(4000):
dice = random.choice(list(descriptions.monsters.keys()))
mons = descriptions.monsters[dice]
monsters.append(Monster(dice, mons[0], mons[1], mons[2], mons[3], mons[4],
mons[5], mons[6], mons[7],mons[8], random.choice(list(range(200))),
random.choice(list(range(200)))))
c.execute("UPDATE players SET status='alive'")
game.gameStatus="started"
sql.commit()
return jsonify(result="ok")
@app.route('/player/')
def playerCount():
return jsonify(result=game.players)
@app.route('/finish/')
def clear():
game.gameStatus="working on it"
c.execute("delete from players")
grid.clearGrid()
sql.commit()
return jsonify(result="cleared")
@app.route('/chat/', methods=["GET"])
def chat():
chatter=[]
message = request.args.get('value')
user = request.args.get('user')
if(message[0:2]=="::"):
c.execute("INSERT INTO chatPending(user,message) VALUES(%s,%s)",
(user,message[2:]))
else:
del chatter[:]
c.execute("SELECT * from chatPending")
row = c.fetchall()
for r in row:
if row is not None:
chatter.append("<p>" + r[0] + ":: " + r[1] + "</p>")
sql.commit()
return jsonify(result=chatter)
@app.route('/load/', methods=["GET"])
def intro():
status=None
answer = request.args.get('value')
ID = request.args.get('ID')
c.execute("SELECT * FROM players WHERE name=%s", (ID,))
row = c.fetchone()
if row is not None:
status = row[3]
if(game.gameStatus=="started" or game.players>=200):
status="access denied"
if(status == None):
c.execute("INSERT INTO players (name, status) VALUES('" + answer + "', 'entering name')")
c.execute("SELECT * FROM players WHERE name=%s",(ID,))
row = c.fetchone()
if row is not None:
status = row[3]
if(status == 'entering name'):
data = "<p>What is in your past: choose one: <ul> <li> Chosen </li> <li> Magician </li> <li> Poet </li></ul></p>"
c.execute("UPDATE players SET status='entering past' WHERE name=%s",(ID,))
c.execute("SELECT * FROM players WHERE name=%s",(ID,))
row = c.fetchone()
if row is not None:
status = row[3]
elif(status == 'entering past'):
data = "<p>What is your class. Choose one: <ul> <li> Warrior </li> <li> Mage </li> <li> Rougue </li> <li> Bard </li></ul></p>"
c.execute("UPDATE players SET status='entering class' WHERE name=%s", (ID,))
c.execute("UPDATE players SET past=%s WHERE name=%s",(answer.capitalize(), ID))
c.execute("SELECT * FROM players WHERE name=%s",(ID,))
row = c.fetchone()
if row is not None:
status = row[3]
elif(status == 'entering class'):
data = "<p>What is your secret code?</p>"
c.execute("UPDATE players SET status='entering code' WHERE name=%s", (ID,))
c.execute("UPDATE players SET class=%s WHERE name=%s",(answer.capitalize(), ID))
c.execute("SELECT * FROM players WHERE name=%s",(ID,))
row = c.fetchone()
if row is not None:
status = row[3]
elif(status == 'entering code'):
data = "<p>OK all set. Waiting on the moderator!</p>"
c.execute("UPDATE players SET status='waiting' WHERE name=%s", (ID,))
c.execute("UPDATE players SET code=%s WHERE name=%s",(answer.capitalize(), ID))
c.execute("SELECT * FROM players WHERE name=%s",(ID,))
game.players+=1
row = c.fetchone()
if row is not None:
status = row[3]
past = row[1]
Class = row[2]
stats = calculator.calculateStats(past)
attacks = []
attackString=""
equipmentString=""
equipment = descriptions.classes[Class.capitalize()]
for a in list(equipment["lHand"][1]["moves"].keys()):
attacks.append(a)
for b in list(equipment["rHand"][1]["moves"].keys()):
attacks.append(b)
for att in attacks:
attackString=attackString + att + ","
for d in equipment:
equipmentString = equipmentString + d[0] + ","
c.execute("UPDATE players SET hp=%s,attack=%s,defense=%s,speed=%s, attacks=%s,"
+ "level=1, experience=0, nextLevel=50, energy=%s,inventory=%s, lHand=%s,rHand=%s,head=%s,hands=%s,chest=%s,legs=%s where name=%s",(stats[0],
stats[1],stats[2],stats[3],attackString,stats[4],equipmentString,
equipment["lHand"][0],equipment["rHand"][0],equipment["Head"][0],
equipment["Hands"][0],equipment["Chest"][0],equipment["Legs"][0],ID))
elif(status == 'waiting'):
data = "<p>Still waiting, please be patient.</p>"
elif(status=="access denied"):
data = "<p>Sorry. The player queue is full.</p>"
else:
data="error"
sql.commit()
return jsonify(result=data)
@app.route('/check/')
def checker():
status=None
ID = request.args.get('user')
c.execute("SELECT * FROM players WHERE name=%s", (ID,))
row = c.fetchone()
if row is not None:
status = row[3]
if(status=="alive"):
data="<p>Ready! Press >> to begin.</p>"
head="ok"
else:
data=""
head="not"
return jsonify(result=data, header=head)
@app.route('/move/')
def move():
y=0
x=0
data=""
answer = request.args.get('value')
ID = request.args.get('ID')
c.execute("SELECT * FROM players WHERE name=%s", (ID,))
row = c.fetchone()
if row is not None:
status = row[3]
x = row[5]
y = row[6]
HP = row[7]
attack = row[8]
defense = row[9]
speed = row[10]
level = row[13]
energy = row[17]
Class = row[2]
past = row[1]
attacks = row[11]
exp = row[14]
nextLevel = row[15]
if(answer=="start"):
c.execute("UPDATE players SET X=%s, y=%s WHERE name=%s",(random.choice(list(range(200))),random.choice(list(range(200))), ID))
data = "You are on a {} tile <br> {} <br>".format(grid.getLandType(x,y), grid.getDesc(x,y))
if(status!="dead"):
if(answer=='profile'):
data = "You're name is {} <br> You are a {} <br> {} <br> your class is: {} <br> your stats are: <br> Level:{} HP:{} <br> Attack:{} <br> Defense:{} <br> Speed:{} <br> Energy:{}".format(ID,past,descriptions.player_backstory[past.lower()],Class,level,HP,attack,defense,speed,energy)
elif(answer=="North" or answer=="N" and status!="fighting"):
if(y>0):
c.execute("UPDATE players SET y=%s WHERE name=%s", (y-1,ID))
data = "You are on a {} tile <br> {} <br>".format(grid.getLandType(x,y), grid.getDesc(x,y))
elif(answer=="East" or answer=="E" and status!="fighting"):
if(x<199):
c.execute("UPDATE players SET X=%s WHERE name=%s", (x+1,ID))
c.execute("SELECT * FROM players WHERE name=%s", (ID,))
row = c.fetchone()
if row is not None:
x = row[5]
data = "You are on a {} tile <br> {} <br>".format(grid.getLandType(x,y), grid.getDesc(x,y))
elif(answer=="South" or answer=="S" and status!="fighting"):
if(y<199):
c.execute("UPDATE players SET y=%s WHERE name=%s", (y+1,ID))
c.execute("SELECT * FROM players WHERE name=%s", (ID,))
row = c.fetchone()
if row is not None:
y = row[6]
data = "You are on a {} tile <br> {} <br>".format(grid.getLandType(x,y), grid.getDesc(x,y))
elif(answer=="West" or answer=="W" and status!="fighting"):
if(x>0):
c.execute("UPDATE players SET X=%s WHERE name=%s", (x-1,ID))
c.execute("SELECT * FROM players WHERE name=%s", (ID,))
row = c.fetchone()
if row is not None:
x = row[5]
data = "You are on a {} tile <br> {} <br>".format(grid.getLandType(x,y), grid.getDesc(x,y))
elif(answer=="Attack"):
for monster in monsters:
if(x==monster.X and y==monster.Y):
data = data + "The {} wakes up, the battle begins".format(monster.name)
c.execute("UPDATE players SET status='fighting' WHERE name=%s",(ID,))
monsterImFighting = monster
elif(answer == "Moves" and status=="fighting"):
c.execute("SELECT * FROM players WHERE name=%s", (ID,))
row = c.fetchone()
if row is not None:
attacks=row[11]
listOfAttacks=attacks.split(",")
for y in listOfAttacks:
data = data + y.capitalize() + "<br>"
elif(status=="fighting"):
for m in monsterImFighting.attacks.keys():
monsterName = m
for a in attacks.split(","):
if(a == answer):
damage = calculator.calculateDamage(attack,monsterImFighting.defense,
descriptions.classes[Class.capitalize()][1]["moves"][answer],
"normal","thunder")
data = data + "you deal {} damage to {}".format(damage,m)
monsterImFighting.hitpoints-=damage
if(monsterImFighting.hitpoints <=0):
data = data + "<br> You killed the {}. You gain {} exp.".format(monsterName,monsterImFighting.drops[0])
c.execute("UPDATE players SET experience=%s WHERE name=%s",(exp + monsterImFighting.drops[0],ID))
c.excecute("SELECT * FROM players WHERE name=%s",(ID,))
row = c.fetchone()
if row is not None:
exp = row[14]
c.excecute("UPDATE players SET status='alive' WHERE name=%s",(ID,))
if(exp >= nextLevel):
data = data + "You've leveled up!!"
c.execute("UPDATE players SET level=%s, attack=%s, defense=%s, speed=%s hp=%s WHERE name=%s",(level + 1,
attack + random.choice(list(range(3))),defense + random.choice(list(range(3))),
speed + random.choice(list(range(3))), HP +random.choice(list(range(20))),ID))
else:
shuf = random.choice(list(monsterImFighting.attacks.keys()))
damageReturn = calculator.calculateReturnDamage(monsterImFighting.attack, defense, monsterImFighting.attacks[shuf])
c.execute("UPDATE players SET hp=%s WHERE name=%s",(HP - damageReturn,ID))
data=data + "{} deals {} damage to you".format(monsterName,damageReturn)
if(HP<=0):
data= data + "You have perished at the hands of a {}".format(monsterName)
c.execute("UPDATE players SET status='dead' WHERE name=%s",(HP - damageReturn,ID))
else:
data = "You are on a {} tile <br> {} <br>".format(grid.getLandType(x,y), grid.getDesc(x,y))
else:
data = "Sorry, but you are dead. Dead people don't move"
sql.commit()
return jsonify(result=data, header=status)
@app.route('/event/')
def eventManager():
data = ""
ID=request.args.get("ID")
c.execute("SELECT * FROM players WHERE name=%s", (ID,))
row = c.fetchone()
if row is not None:
x = row[5]
c.execute("SELECT * FROM players WHERE name=%s", (ID,))
row = c.fetchone()
if row is not None:
y = row[6]
for monster in monsters:
if(monster.X == x and monster.Y == y):
data = "A {} is sleeping nearby!".format(monster.name)
return jsonify(result=data, header=len(monsters))
我在网上寻找解决方案,他们都提到这与您一次与服务器建立的连接数量有关(至少我是这样认为的),但解决方案似乎...没有定论,尤其是关于在 pythonanywhere 上托管您的应用程序时如何处理这个问题。
如有任何帮助,我们将不胜感激!
最佳答案
PythonAnywhere 开发者在这里。我真的建议你通过 SQLalchemy 而不是直接使用 MySQL——它是一个位于你的代码和 mysql.connector 东西之间的库,它应该使你与所有连接管理东西隔离开来。这适用于 PythonAnywhere 或任何其他托管平台。
Flask 教程对使用 SQLAlchemy 有一些很好的提示。
关于python - 将mysql与pythonanywhere一起使用时出现错误4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27552094/
我正在处理一组标记为 160 个组的 173k 点。我想通过合并最接近的(到 9 或 10 个组)来减少组/集群的数量。我搜索过 sklearn 或类似的库,但没有成功。 我猜它只是通过 knn 聚类
我有一个扁平数字列表,这些数字逻辑上以 3 为一组,其中每个三元组是 (number, __ignored, flag[0 or 1]),例如: [7,56,1, 8,0,0, 2,0,0, 6,1,
我正在使用 pipenv 来管理我的包。我想编写一个 python 脚本来调用另一个使用不同虚拟环境(VE)的 python 脚本。 如何运行使用 VE1 的 python 脚本 1 并调用另一个 p
假设我有一个文件 script.py 位于 path = "foo/bar/script.py"。我正在寻找一种在 Python 中通过函数 execute_script() 从我的主要 Python
这听起来像是谜语或笑话,但实际上我还没有找到这个问题的答案。 问题到底是什么? 我想运行 2 个脚本。在第一个脚本中,我调用另一个脚本,但我希望它们继续并行,而不是在两个单独的线程中。主要是我不希望第
我有一个带有 python 2.5.5 的软件。我想发送一个命令,该命令将在 python 2.7.5 中启动一个脚本,然后继续执行该脚本。 我试过用 #!python2.7.5 和http://re
我在 python 命令行(使用 python 2.7)中,并尝试运行 Python 脚本。我的操作系统是 Windows 7。我已将我的目录设置为包含我所有脚本的文件夹,使用: os.chdir("
剧透:部分解决(见最后)。 以下是使用 Python 嵌入的代码示例: #include int main(int argc, char** argv) { Py_SetPythonHome
假设我有以下列表,对应于及时的股票价格: prices = [1, 3, 7, 10, 9, 8, 5, 3, 6, 8, 12, 9, 6, 10, 13, 8, 4, 11] 我想确定以下总体上最
所以我试图在选择某个单选按钮时更改此框架的背景。 我的框架位于一个类中,并且单选按钮的功能位于该类之外。 (这样我就可以在所有其他框架上调用它们。) 问题是每当我选择单选按钮时都会出现以下错误: co
我正在尝试将字符串与 python 中的正则表达式进行比较,如下所示, #!/usr/bin/env python3 import re str1 = "Expecting property name
考虑以下原型(prototype) Boost.Python 模块,该模块从单独的 C++ 头文件中引入类“D”。 /* file: a/b.cpp */ BOOST_PYTHON_MODULE(c)
如何编写一个程序来“识别函数调用的行号?” python 检查模块提供了定位行号的选项,但是, def di(): return inspect.currentframe().f_back.f_l
我已经使用 macports 安装了 Python 2.7,并且由于我的 $PATH 变量,这就是我输入 $ python 时得到的变量。然而,virtualenv 默认使用 Python 2.6,除
我只想问如何加快 python 上的 re.search 速度。 我有一个很长的字符串行,长度为 176861(即带有一些符号的字母数字字符),我使用此函数测试了该行以进行研究: def getExe
list1= [u'%app%%General%%Council%', u'%people%', u'%people%%Regional%%Council%%Mandate%', u'%ppp%%Ge
这个问题在这里已经有了答案: Is it Pythonic to use list comprehensions for just side effects? (7 个答案) 关闭 4 个月前。 告
我想用 Python 将两个列表组合成一个列表,方法如下: a = [1,1,1,2,2,2,3,3,3,3] b= ["Sun", "is", "bright", "June","and" ,"Ju
我正在运行带有最新 Boost 发行版 (1.55.0) 的 Mac OS X 10.8.4 (Darwin 12.4.0)。我正在按照说明 here构建包含在我的发行版中的教程 Boost-Pyth
学习 Python,我正在尝试制作一个没有任何第 3 方库的网络抓取工具,这样过程对我来说并没有简化,而且我知道我在做什么。我浏览了一些在线资源,但所有这些都让我对某些事情感到困惑。 html 看起来
我是一名优秀的程序员,十分优秀!