天天看點

python編寫webapi讀取mdb資料使用json格式響應用戶端請求

想做個自動應答機器人,通過webapi提供服務,原理:判斷關鍵字,到資料庫查詢相關内容,以json格式回報給用戶端。

1、建立autoreply資料庫,建立reply表,表中包含kename(短文本)和reponse(短文本)字段。

 mdb資料庫:D:\spiderdocs\autoreply.accdb

python編寫webapi讀取mdb資料使用json格式響應用戶端請求

2、編寫python代碼。

import pyodbc
from flask import Flask, request, jsonify

# Connect to the MS Access database file
conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=D:\spiderdocs\autoreply.accdb;')

# Define the Flask app
app = Flask(__name__)

# Define the API endpoint
@app.route('/api/autoreply', methods=['GET'])
def autoreply():
    # Get the key name from the query parameters
    key_name = request.args.get('keyname')

    # Query the database for the response based on the key name
    cursor = conn.cursor()
    cursor.execute('SELECT response FROM reply WHERE keyname = ?', key_name)
    row = cursor.fetchone()

    # If there is no response for the key name, return an error message
    if row is None:
        return jsonify({'error': f'No response found for key name "{key_name}"'})

    # Otherwise, return the response
    response = row[0]
    return jsonify({'response': response})

# Start the Flask app
if __name__ == '__main__':
    app.run()
           

3、編寫用戶端代碼(delphi)

通路格式:

http://localhost:5000/api/autoreply?keyname=你好
           

4、測試一下。

5、使用delphi編制用戶端。

1)下載下傳superobject單元檔案。

https://download.csdn.net/download/lwson2008/13095438

2)form上放置edit、memo、button、idhttp元件。

python編寫webapi讀取mdb資料使用json格式響應用戶端請求

 3)編制代碼:

uses 單元檔案:

uses 
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient,
  IdHTTP, StdCtrls, IdURI, SuperObject;
           

a、httpEncode函數:

function HttpEncode(S:AnsiString):string;
var
  P:^Byte;
  I:Cardinal;
begin
  Result:='';
  P:[email protected][1];
  Result:=Format('%%%x',[Ord(P^)]);
  for I := 1 to Length(S)-1 do
  begin
    Inc(P);
    Result:=Format('%s%%%x',[Result,Ord(P^)]);
  end;
end;
           

b、SendRequest函數:注意AnsiToUtf8函數很重要,否則會出現亂碼。

function TForm1.SendRequest(const KeyName: string): string;
var
  HTTP: TIdHTTP;
  tmpstr:string;
begin
  HTTP := TIdHTTP.Create(nil);
  try
    Result := HTTP.Get('http://localhost:5000/api/autoreply?keyname='+HttpEncode(AnsiToUtf8(keyname )));      
  finally
    HTTP.Free;
  end;
end;
           

c、按鈕事件:

procedure TForm1.btnSendRequestClick(Sender: TObject);
var
  JsonString: string;
  Json: ISuperObject;

begin

    JsonString := SendRequest(edtKeyName.Text);
    Json := SO(JsonString);
    if Json.O['response'] <> nil then
    begin
      ShowMessage(Json.O['response'].AsString);
      memResponse.Lines.Text := Json.O['response'].AsString;
    end;
end;
           

結果:

服務端:

python編寫webapi讀取mdb資料使用json格式響應用戶端請求

 用戶端:

python編寫webapi讀取mdb資料使用json格式響應用戶端請求