想做个自动应答机器人,通过webapi提供服务,原理:判断关键字,到数据库查询相关内容,以json格式反馈给客户端。
1、创建autoreply数据库,创建reply表,表中包含kename(短文本)和reponse(短文本)字段。
mdb数据库:D:\spiderdocs\autoreply.accdb
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组件。
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:=@S[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;
结果:
服务端:
客户端: