我堂哥的女儿叫我什么在贷款软件

玩蛇网提供最新Python编程技术信息以及Python资源下载!
您现在的位置:
python开发WEB服务中数据库链接释放应该怎么做?
用tornado开发web service服务。服务端根据接收到的json数据对mysql数据库进行查询,并把结果反馈给用户。采用sqlalchemy对数据库进行操作,以下对数据库链接的创建,释放是否合理呢?
def __init__(self,db_ip='',db_name='',db_user='',db_pass='',db_charset=''):
self.db_str = 'mysql+pymysql://'+db_user+':'+db_pass+'@'+db_ip+':3306/'+db_name+'?'+'charset='+db_charset
self.engine = create_engine(self.db_str, encoding='utf-8', echo=False)
self.dbsession = sessionmaker(bind=self.engine)
def return_dbsession(self):
return self.dbsession
def close_session(self):
self.session.close()
database = db(db_ip='127.0.0.1', db_name='data_utf', db_user='root', db_pass='root', db_charset='utf8')
处理post请求代码如下
class rcvRequest(tornado.web.Request):
session = scoped_session(database.return_dbsession())()
response = []
for ctt in session.query(table).filter(table.ID == id):
response.append(ctt)
self.write(str(response))
session.close()
还是建议找个ORM吧。你这样一个链接就请求一次搞不好数据服务就挂掉了。不合理,每来一次请求就建立一次连接不是很浪费吗?sqlalchemy可以很好的帮你管理连接池,找找资料,用连接池吧.代码调整为以下这种方式是否合理?def db(db_ip='',db_name='',db_user='',db_pass='',db_charset=''):
db_str = 'mysql+pymysql://'+db_user+':'+db_pass+'@'+db_ip+':3306/'+db_name+'?'+'charset='+db_charset
engine = create_engine(self.db_str, encoding='utf-8', echo=False)
dbsession = sessionmaker(bind=self.engine)
return dbsession
database =db(db_ip='127.0.0.1', db_name='data_utf', db_user='root', db_pass='root', db_charset='utf8')
class rcvRequest(tornado.web.Request):
def initialize(self):
self.session = scoped_session(database)()
@tornado.gen.coroutine
def post(self):
response = []
for ctt in self.session.query(table).filter(table.ID == id):
response.append(ctt)
self.write(str(response))
def on_finish(self):
self.session.close()请参考
玩蛇网文章,转载请注明出处和文章网址:/wenda/wd14017.html []
我要小额赞助,鼓励作者写出更好的教程↓↓↓】
玩蛇网Python QQ群,欢迎加入: ①
修订日期:日 - 11时27分45秒
发布自玩蛇网
我要分享到:
评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
必知PYTHON教程
Must Know PYTHON Tutorials
必知PYTHON模块
Must Know PYTHON Modules
最新内容 NEWS
图文精华 RECOMMEND
热点文章 HOT
Navigation
玩蛇网Python之家,简称玩蛇网,是一个致力于推广python编程技术、程序源码资源的个人网站。站长 斯巴达 是一位 长期关注 软件、互联网、服务器与各种开发技术的Python爱好者,建立本站旨在与更多朋友分享派森编程的乐趣!
本站团队成员: 斯巴达
欢迎加入团队...cmdbuild的部署可以查看文章:http://
部署成功后,访问http://192.168.1.1:8080/cmdbuild/services/soap/ 就能看到所有的webservice方法,证明server这边已经ready了
cmdbuild webservice官方说明文档:http://download.csdn.net/detail/siding159/7888309
下面是使用python开发webservice client的方法:
python的webservice模块有很多,这里使用suds来进行连接
可以通过 easy_install suds来安装suds,十分方便
suds官方文档:https://fedorahosted.org/suds/wiki/Documentation
suds是通过logging来实现日志的,所以配置logging后,就可以看到soap连接过程中的所有数据
import logging
logging.basicConfig(level=logging.DEBUG, filename='myapp.log')
logging.getLogger('suds.client').setLevel(logging.DEBUG)
# logging.getLogger('suds.transport').setLevel(logging.DEBUG)
# logging.getLogger('suds.xsd.schema').setLevel(logging.DEBUG)
# logging.getLogger('suds.wsdl').setLevel(logging.DEBUG)
suds提供了四种日志类型,可以根据需要来配置
from suds.client import Client
url = 'http://192.168.8.190:8080/cmdbuild/services/soap/Private?wsdl'
client = Client(url)
print client
r=client.service.getCard('Cabinet',2336)
实例化Client后,可以print client来输出次webservice提供的接口,也就是wsdl文件的说明
通过r=client.service.getCard('Cabinet',2336)来调用webservice的getCard接口,并输入参数,print client的输出结果会有每个接口需要输入的参数说明
但是这样连接后,会报错:suds.WebFault: Server raised fault: 'An error was discovered processing the &wsse:Security& header'
因为cmdbuild需要wsse安全验证
4.wsse安全验证
为client实例设置wsse参数
from suds.wsse import *
from suds.client import Client
url = 'http://192.168.8.190:8080/cmdbuild/services/soap/Private?wsdl'
client = Client(url)
security = Security()
token = UsernameToken('admin', 'admin')
security.tokens.append(token)
client.set_options(wsse=security)
r=client.service.getCard('Cabinet',2336)
UsernameToken的参数是访问的账号和密码继续运行程序后,可能会报错:suds.WebFault: Server raised fault: 'The security token could not be authenticated or authorized'&解决方法是,把cmdb的auth配置文件的force.ws.password.digest参数设置为false,并重启tomcat,auth.conf路径 tomcat/webapps/WEB-INI/conf/auth.conf
5.处理返回来的xml
继续运行,会报错:xml.sax._exceptions.SAXParseException: &unknown&:2:0: syntax error
原因是程序在解析返回的xml文件的时候出错了,通过日志,我们可以看到返回来的body是这样的
--uuid:b16cf808-f566-4bad-a92c-a7d303d33211
Content-Type: application/xop+ charset=UTF-8; type="text/xml";
Content-Transfer-Encoding: binary
Content-ID: &root.message@cxf.apache.org&
&soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"&&soap:Body&&ns2:getCardResponse xmlns:ns2="http://soap.services.cmdbuild.org"&&ns2:return&&ns2:attributeList&&ns2:name&User&/ns2:name&&ns2:value&admin&/ns2:value&&/ns2:attributeList&&ns2:attributeList&&ns2:code&6084&/ns2:code&&ns2:name&CabinetStatus&/ns2:name&&ns2:value&终止&/ns2:value&&/ns2:attributeList&&ns2:attributeList&&ns2:name&RentalAmount&/ns2:name&&ns2:value&9000.00&/ns2:value&&/ns2:attributeList&&ns2:attributeList&&ns2:name&Description&/ns2:name&&ns2:value&机房 Room 1 D14&/ns2:value&&/ns2:attributeList&&ns2:attributeList&&ns2:name&BeginDate&/ns2:name&&ns2:value&12/08/14 18:03:17&/ns2:value&&/ns2:attributeList&&ns2:attributeList&&ns2:name&Contract&/ns2:name&&ns2:value&&/ns2:value&&/ns2:attributeList&&ns2:attributeList&&ns2:name&Code&/ns2:name&&ns2:value&D14&/ns2:value&&/ns2:attributeList&&ns2:attributeList&&ns2:code&168&/ns2:code&&ns2:name&Trusteeship&/ns2:name&&ns2:value&科技有限公司&/ns2:value&&/ns2:attributeList&&ns2:attributeList&&ns2:name&Notes&/ns2:name&&ns2:value&&/ns2:value&&/ns2:attributeList&&ns2:attributeList&&ns2:name&Status&/ns2:name&&ns2:value&N&/ns2:value&&/ns2:attributeList&&ns2:attributeList&&ns2:code&2325&/ns2:code&&ns2:name&Room&/ns2:name&&ns2:value&机房Room 1&/ns2:value&&/ns2:attributeList&&ns2:attributeList&&ns2:name&StartDate&/ns2:name&&ns2:value&23/09/10&/ns2:value&&/ns2:attributeList&&ns2:attributeList&&ns2:name&Id&/ns2:name&&ns2:value&2336&/ns2:value&&/ns2:attributeList&&ns2:attributeList&&ns2:name&Capacity&/ns2:name&&ns2:value&0&/ns2:value&&/ns2:attributeList&&ns2:attributeList&&ns2:name&NoUsed&/ns2:name&&ns2:value&0&/ns2:value&&/ns2:attributeList&&ns2:attributeList&&ns2:name&IdClass&/ns2:name&&ns2:value&42216&/ns2:value&&/ns2:attributeList&&ns2:attributeList&&ns2:name&CibinetNUm&/ns2:name&&ns2:value&15&/ns2:value&&/ns2:attributeList&&ns2:beginDate&T18:03:17.839+08:00&/ns2:beginDate&&ns2:className&Cabinet&/ns2:className&&ns2:id&2336&/ns2:id&&ns2:metadata&&ns2:key&runtime.privileges&/ns2:key&&ns2:value&write&/ns2:value&&/ns2:metadata&&ns2:user&admin&/ns2:user&&/ns2:return&&/ns2:getCardResponse&&/soap:Body&&/soap:Envelope&
--uuid:b16cf808-f566-4bad-a92c-a7d303d33211--
发现在xml字符串之外还有很多没用的信息,所以我们需要在接受了返回之后,对返回结果进行处理(把它转化成标准的xml字符串)后,再进行xml的解析
from suds.wsse import *
from suds.client import Client
from suds.plugin import MessagePlugin
url = 'http://192.168.8.190:8080/cmdbuild/services/soap/Private?wsdl'
class MyPlugin(MessagePlugin):
def received(self, context):
reply_new=re.findall("&soap:Envelope.+&/soap:Envelope&",context.reply,re.DOTALL)[0]
context.reply=reply_new
client = Client(url, plugins=[MyPlugin()])
security = Security()
token = UsernameToken('admin', 'admin')
security.tokens.append(token)
client.set_options(wsse=security)
r=client.service.getCard('Cabinet',2336)
做法就是定义一个钩子(hook),在接收返回后,把需要的xml字符串抽取处理,由于xml中可能有换行符,所以加入了re.DOTALL
这样程序就能正常访问webservice了,返回值:
attributeList[] =
(attribute){
name = "User"
value = "admin"
(attribute){
code = "6084"
name = "CabinetStatus"
value = "合同"
(attribute){
name = "RentalAmount"
value = "9000.00"
(attribute){
name = "Description"
value = "机房Room 1 D14"
(attribute){
name = "BeginDate"
value = "12/08/14 18:03:17"
(attribute){
name = "Contract"
value = None
(attribute){
name = "Code"
value = "D14"
(attribute){
code = "168"
name = "Trusteeship"
value = "科技有限公司"
(attribute){
name = "Notes"
value = None
(attribute){
name = "Status"
value = "N"
(attribute){
code = "2325"
name = "Room"
value = "机房Room 1"
(attribute){
name = "StartDate"
value = "23/09/10"
(attribute){
name = "Id"
value = "2336"
(attribute){
name = "Capacity"
value = "0"
(attribute){
name = "NoUsed"
value = "0"
(attribute){
name = "IdClass"
value = "42216"
(attribute){
name = "CibinetNUm"
value = "15"
beginDate =
18:03:17.000839
className = "Cabinet"
metadata[] =
(metadata){
key = "runtime.privileges"
value = "write"
user = "admin"
一看我就晕了,这是什么数据结构?type返回的类型是instance
不过我发现可以用列表的方式来访问它,例如输入r[0][1][2] 返回的是&合同&,不知道还有没有更好的返回结果解析方式
url的说明:soap的url必须要加端口,例如8080,不然会返回&urllib2.URLError: &urlopen error [Errno 111] Connection refused&
CMDBuild更新后,请求接口的时候客户端报错:
xml.sax._exceptions.SAXParseException:&&unknown&:1:0:&syntax&error
查看客户端的日志显示:
A&security&error&was&encountered&when&verifying&the&message
查看CMDBuild的日志,显示:
Caused&by:&org.mon.ext.WSSecurityException:&BSP:R4201:&Any&PASSWORD&MUST&specify&a&Type&attribute
即任何密码都必须定义Type属性。
查了下相关的资料:
发现需要在Password标签中设置属性:
Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText'
再查看了suds的文档,发现可以通过设置Hook来修改suds发送到cmdbuild的请求数据:
class MyPlugin(MessagePlugin):
def marshalled(self, context):
pass_type = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText'
password = context.envelope.getChild('Header').getChild('Security').getChild('UsernameToken').getChild(
'Password')
password.set('Type', pass_type)
marshalled方法会在suds发送数据给cmdbuild前执行。
&转载请带上我(/EditPosts.aspx?postid=3963831)
阅读(...) 评论()关于webservice连接数据库的问题
我在webservice中连接mysql一直连不上&就大神帮帮小弟&&下面是异常和代码
异常:System.Data.SqlClient.SqlException:&用户&'xingfukun'&登录失败。
&&&在&System.Data.SqlClient.SqlInternalConnection.OnError(SqlException&exception,&Boolean&breakConnection,&Action`1&wrapCloseInAction)
&&&在&System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject&stateObj,&Boolean&callerHasConnectionLock,&Boolean&asyncClose)
&&&在&System.Data.SqlClient.TdsParser.TryRun(RunBehavior&runBehavior,&SqlCommand&cmdHandler,&SqlDataReader&dataStream,&BulkCopySimpleResultSet&bulkCopyHandler,&TdsParserStateObject&stateObj,&Boolean&&dataReady)
&&&在&System.Data.SqlClient.TdsParser.Run(RunBehavior&runBehavior,&SqlCommand&cmdHandler,&SqlDataReader&dataStream,&BulkCopySimpleResultSet&bulkCopyHandler,&TdsParserStateObject&stateObj)
&&&在&System.Data.pleteLogin(Boolean&enlistOK)
&&&在&System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo&serverInfo,&String&newPassword,&SecureString&newSecurePassword,&Boolean&ignoreSniOpenTimeout,&TimeoutTimer&timeout,&SqlConnection&owningObject,&Boolean&withFailover)
&&&在&System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo&serverInfo,&String&newPassword,&SecureString&newSecurePassword,&Boolean&redirectedUserInstance,&SqlConnection&owningObject,&SqlConnectionString&connectionOptions,&SqlCredential&credential,&TimeoutTimer&timeout)
&&&在&System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection&owningObject,&TimeoutTimer&timeout,&SqlConnectionString&connectionOptions,&SqlCredential&credential,&String&newPassword,&SecureString&newSecurePassword,&Boolean&redirectedUserInstance)
&&&在&System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity&identity,&SqlConnectionString&connectionOptions,&SqlCredential&credential,&Object&providerInfo,&String&newPassword,&SecureString&newSecurePassword,&SqlConnection&owningObject,&Boolean&redirectedUserInstance)
&&&在&System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions&options,&DbConnectionPoolKey&poolKey,&Object&poolGroupProviderInfo,&DbConnectionPool&pool,&DbConnection&owningConnection)
&&&在&System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection&owningConnection,&DbConnectionPool&pool,&DbConnectionOptions&options,&DbConnectionPoolKey&poolKey)
&&&在&System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection&owningObject)
&&&在&System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection&owningObject)
&&&在&System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection&owningObject,&UInt32&waitForMultipleObjectsTimeout,&Boolean&allowCreate,&Boolean&onlyOneCheckConnection,&DbConnectionInternal&&connection)
&&&在&System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection&owningObject,&TaskCompletionSource`1&retry,&DbConnectionInternal&&connection)
&&&在&System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection&owningConnection,&TaskCompletionSource`1&retry,&DbConnectionInternal&&connection)
&&&在&System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection&outerConnection,&DbConnectionFactory&connectionFactory,&TaskCompletionSource`1&retry)
&&&在&System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1&retry)
&&&在&System.Data.SqlClient.SqlConnection.Open()
&&&在&WebApplication2.WebService1.GetUserInfo()&位置&e:\C#\WebApplication2\WebApplication2\WebService1.asmx.cs:行号&35
&&&&&&&&[WebMethod]
&&&&&&&&public&DataSet&GetUserInfo()
&&&&&&&&&&&&//连接SQL数据库
&&&&&&&&&&&&System.Data.SqlClient.SqlConnection&SqlCnn&=&new&System.Data.SqlClient.SqlConnection("Server=&DataBase=&user&id=&password='xing';");
&&&&&&&&&&&&//打开数据库连接
&&&&&&&&&&&&SqlCnn.Open();
&&&&&&&&&&&&//加入SQL语句,实现数据库功能
&&&&&&&&&&&&System.Data.SqlClient.SqlDataAdapter&SqlDa&=&new&System.Data.SqlClient.SqlDataAdapter("select&*&from&booka",&SqlCnn);
&&&&&&&&&&&&//创建缓存
&&&&&&&&&&&&DataSet&DS&=&new&DataSet();
&&&&&&&&&&&&//将SQL语句放入缓存
&&&&&&&&&&&&SqlDa.Fill(DS);
&&&&&&&&&&&&//释放资源
&&&&&&&&&&&&SqlDa.Dispose();
&&&&&&&&&&&&//关闭数据库
&&&&&&&&&&&&SqlCnn.Close();
&&&&&&&&&&&&return&DS;
对webservice不熟悉。但是从你的这个错误日志里面看CompleteLogin()后,tryrun()才出错。怀疑是你的用户权限不够,或者其他的原因。你在各个操作后记录一下日志,确认一下出错的位置。如果能够捕捉exception的话,建议你把exception的内容打印到日志中,看看到底是什么原因。
用户&'xingfukun'&登录失败。
同样的机器上,直接用MYQL命令行工具是否能连接上?
回复
即使是一小步也想与你分享}

我要回帖

更多关于 堂哥的儿子叫我什么 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信