当前位置:   article > 正文

基于Flask创建Python服务端,并调用Python客户端、C#客户端_python flask 和c#

python flask 和c#

服务端

Python服务端

Python的服务端调用代码如下所示:

from flask import Flask, request

class AiServer(object):
    def __init__(self):
        server = Flask(__name__)
        server.route('/post', methods=['POST'])(self.post)
        server.run(host="0.0.0.0", port=8000, threaded=True)

    def post(self):
        if request.method == "POST":
            print("get post")
            response_data = request.json.get('data')
            print("response_data", response_data)
            return "Hello"


if __name__ == '__main__':
    AiServer()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

客户端

Python客户端实现如下所示:

Python客户端

import requests

if __name__ == '__main__':

    # post 请求
    url = "http://localhost:8000/post"
    data = "num"
    r = requests.post(url, json={"data": data})
    print(r.text)
    r = requests.post(url, json={"data": data})
    print(r.text)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

C#客户端

C#客户端实现如下所示:

using System;

using System.IO;
using System.Net;
using System.Text;

namespace SabberStoneBasicAI
{
	internal class Program
	{
		private static readonly Random Rnd = new Random();

		private static void Main1()
		{
			Console.WriteLine("Starting test setup.");
			string url = "http://localhost:8000/post";
			HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
			request.Method = "POST";
			//request.Timeout = "800"; // 设置请求超时,单位毫秒。
			request.ContentType = "application/json";
			string postData = "{\"data\":\"value1\"}";
			byte[] data = Encoding.UTF8.GetBytes(postData);
			request.ContentLength = data.Length;

			// 定义请求流
			Stream myRequestStream = request.GetRequestStream();
			myRequestStream.Write(data, 0, data.Length);
			myRequestStream.Close();
			// 发送
			HttpWebResponse response = (HttpWebResponse)request.GetResponse();

			// 获取返回值
			Stream myResponseStream = response.GetResponseStream();
			StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
			string retString = myStreamReader.ReadToEnd();
			Console.WriteLine(retString);

			Console.WriteLine("Test ended!");
			Console.ReadLine();
		}
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/748444
推荐阅读
相关标签
  

闽ICP备14008679号