python窗体程序和网站交互_四、基于Flask的Python和C#交互(中篇)

1.Flask环境安装

首先,进行Flask相应依赖库的环境安装(python这些我就不提了)。最基本的一些依赖库还是需要我们进行安装的,如下图所示。直接本地安装的话就照这个安装,离线下载的话就下载好对应的*.whl文件依次安装即可,其他用Pycharm啥的你就直接找Flask安装就得了,我也不多介绍。

2.Flask脚本

简单的创建一个Python程序,暂定为CreateFlask.cs。代码如下,网络地址为127.0.0.1,若是远程调用则该处需要更改为0.0.0.0。

##远程访问的话,设置端口为host=0.0.0.0##

##重点## 0.0.0.0表示任意地址,不能直接使用,使用时应该使用一个确定地址##

##本地仍旧是访问http://127.0.0.1:8000/,远程访问的话就把0.0.0.0替换成服务器的IP地址##

#!/usr/bin/python#-*- coding: UTF-8 -*-#python服务器如果需要访问静态的文件,都需要放到static这个指定的文件夹。

from flask importFlask, jsonify, requestfrom flask importrender_templatefrom wtforms importStringField, Formfrom wtforms.validators importDataRequiredimportAddNum

app= Flask(__name__)

app.logger.info('Finished Start Flask!')#开始数据转移

@app.route('/add/', methods=['POST'])def startTransfer(name=None):if request.method == 'POST':

receiveData= request.data.decode('utf-8') #为了兼容中文输入

para =str(receiveData)print(para) #输出接收到的信息

array = str(para).split('#')

sum= AddNum.Add(array[1], array[2])returnstr(sum)if __name__ == '__main__':

app.run(host='127.0.0.1', port=8000, debug=False, threaded=True)#debug=True 时设置的多线程无效

#多线程和多进程功能只能开一个 1.processes=True 2.threaded=True

#!/usr/bin/python#-*- coding: UTF-8 -*-

defAdd(para1,para2):return int(para1)+int(para2)

如下图所示,启动FLask服务器成功!

3.C#程序

简单的建立一个window窗体进行编辑。添加控件和响应事件,如下图所示,Url是功能网址;输入参数后点击开始计算,成功输出结果。

  

usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.IO;usingSystem.Linq;usingSystem.Net;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;namespaceFlaskClient

{public partial classFlaskClient : Form

{publicFlaskClient()

{

InitializeComponent();

}private void buttonStart_Click(objectsender, EventArgs e)

{string log = "";//错误信息

string Url = this.textBoxUrl.Text;//功能网址

string add1 = this.textBoxAdd1.Text;string add2 = this.textBoxAdd2.Text;string jsonParams = "#" + add1 + "#" + add2 + "#";string result =RequestsPost(Url, jsonParams);if (result == null)

{

log= "Failed to Connect Flask Server!";

}else{if (result.Contains("default"))

{

log= "There is an error running the algorithm." + "\r\n" +result;

}else{this.textBoxSum.Text =result;

log= "Test Successed!";

}

}

MessageBox.Show(log);

}///

///通过网络地址和端口访问数据///

/// 网络地址

/// json参数

///

public string RequestsPost(string Url, stringjsonParas)

{string postContent = "";string strURL =Url;//创建一个HTTP请求

HttpWebRequest request =(HttpWebRequest)WebRequest.Create(strURL);//Post请求方式

request.Method = "POST";//内容类型

request.ContentType = "application/json";//设置参数,并进行URL编码

string paraUrlCoded = jsonParas;//System.Web.HttpUtility.UrlEncode(jsonParas);

byte[] payload;//将Json字符串转化为字节

payload =System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);//设置请求的ContentLength

request.ContentLength =payload.Length;//发送请求,获得请求流

Stream writer;try{

writer= request.GetRequestStream();//获取用于写入请求数据的Stream对象

}catch(Exception)

{

writer= null;

MessageBox.Show("连接服务器失败!");return null;

}//将请求参数写入流

writer.Write(payload, 0, payload.Length);

writer.Close();//关闭请求流

HttpWebResponse response;try{//获得响应流

response =(HttpWebResponse)request.GetResponse();

}catch(WebException ex)

{

response= ex.Response asHttpWebResponse;

postContent= "default: The response is null." + "\r\n" + "Exception:" +ex.Message;

}if (response != null)

{try{

Stream s=response.GetResponseStream();

StreamReader sRead= newStreamReader(s);

postContent=sRead.ReadToEnd();

sRead.Close();

}catch(Exception e)

{

postContent= "default: The data stream is not readable." + "\r\n" +e.Message;

}

}return postContent;//返回Json数据

}

}

}

初始代码就这样了,后续其他功能扩展也就在这个基础上进行就可以了,C#这边只需要添加相应的Url和输入参数即可。Flask脚本那边就增加对应的路由,搭配起来操作不会太麻烦。下篇会讲一下Flask的主要用途,用于界面设计的搭配,这块的话就完全可以去除掉C#的用处,从网页端即可进行服务器的一些操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值