毛狗 發表於 2024-4-12 10:53:38

rust实现post小程序(完整代码)

<p>主要是白天折磨了半天,无论如何post出去都不能成功,搞得我专门修改了一堆server的代码,以拦截任何访问服务器的数据,结果还是返回502,结果晚上回来一遍过,也真是奇怪的不行。先把一遍过的代码放出来,防止哪天又卡在这儿过不去。</p>
<div class="jb51code"><pre class="brush:plain;">//main.rs
use reqwest::Error;
//main.rs
async fn post_request() -&gt; Result&lt;(), Error&gt; {
    let url = "http://localhost:30241/dfc/get_block_stock";
    let json_data = r#"{"block_source": "gnn"}"#;
    let client = reqwest::Client::new();
    let response = client
      .post(url)
      .header("Content-Type", "application/json")
      .body(json_data.to_owned())
      .send()
      .await?;
    println!("Status Code: {}", response.status());
    let response_body = response.text().await?;
    println!("Response body: \n{}", response_body);
    Ok(())
}
#
async fn main() -&gt; Result&lt;(), Error&gt; {
    post_request().await?;
    Ok(())
}</pre></div>
<p>Cargo.toml文件如下:</p>
<div class="jb51code"><pre class="brush:plain;">
name = "untitled"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

tokio = { version = "1.15", features = ["full"] }
reqwest = { version = "0.11.22", features = ["json"] }</pre></div>
<p>意思很简单,就是访问路径为/dfc/get_block_stock,json数据为:</p>
<div class="jb51code"><pre class="brush:json;">{"block_source": "gnn"}</pre></div>
<p>后面就是打印结果了。居然直接一遍过了,在公司可是花了好几小时查遍了所有资料,也改遍了服务器的代码。</p>
<p>最后再贴出服务器的python测试代码:my_http_server.py</p>
<div class="jb51code"><pre class="brush:py;">from sanic import Sanic
from sanic import response, request
from sanic_cors import CORS
app = Sanic(name='my-http-server')
CORS(app)
def success_msg(err_code=0):
    res = dict()
    res["err_code"] = err_code
    res["err_msg"] = "success"
    return res
@app.middleware("response")
def cors_middle_res(request: request.Request, response: response.HTTPResponse):
    """跨域处理"""
    allow_origin = '*'
    response.headers.update(
      {
            'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers': 'Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization',
      }
    )
@app.route("/dfc/get_block_stock", methods=['POST'])
async def order_buy_sell(request):
    print("order_buy_sell: from: {}, path: {}, data: {}".format(request.socket, request.path, request.json))
    res = success_msg(0)
    result = dict()
    res["result"] = result
    return response.json(res)</pre></div>
<p>然后是main.py</p>
<div class="jb51code"><pre class="brush:py;">from my_http_server import app
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    try:
      port = 30241
      print("my-http-server will started, serving at http://localhost:{}".format(port))
      app.run(host="0.0.0.0", port=port)
    except KeyboardInterrupt:
      print("python-sanic-http-server error.")</pre></div>
<p>最后由于服务器运行用到了sanic组件和一个跨域组件,所以最后记得</p>
<div class="jb51code"><pre class="brush:bash;">pip install sanic
pip install sanic_cors</pre></div>
<p>到此这篇关于rust实现一个post小程序的文章就介绍到这了,更多相关rust post小程序内容请搜索琼殿技术社区以前的文章或继续浏览下面的相关文章希望大家以后多多支持琼殿技术社区!</p>
                           
                            <div class="art_xg">
                              <b>您可能感兴趣的文章:</b><ul><li>Rust 连接 PostgreSQL 数据库的详细过程</li></ul>
                            </div>

                        </div>
                        <!--endmain-->
頁: [1]
查看完整版本: rust实现post小程序(完整代码)