我构建了一个 Vapor 4 应用程序,目前部署在本地 Ubuntu 18 服务器虚拟机上,在 NGINX 后面运行并为用户提供服务,没有任何问题。
现在我希望我的一个网络服务器路由通过执行 Bash 命令来对特定的 POST 做出反应Process(这是为了通过slack-cli将消息发送到专用的 Slack 通道,这是我已经用于其他目的的工具,即已经在我的开发机器和 Ubuntu 服务器上配置并运行)。
使用以下代码,当我在本地计算机上运行 Vapor 应用程序时,一切都按预期工作(即:在 POST 到路由之后,预期消息立即出现在 Slack 通道中):
// What follows is placed inside my dedicated app.post route, after checking the response is valid...
let slackCLIPath = "/home/linuxbrew/.linuxbrew/bin/" // This is the slack-cli path on the Linux VM; I swap it with "/opt/homebrew/bin/" when running the app on my local Mac
_ = runShellScript("\(slackCLIPath)slack chat send …Run Code Online (Sandbox Code Playgroud) 我正在使用 Vapor Swift 构建一个开放 AI 聊天流后端。它使用 MacPaw 的OpenAI包装器连接到 Open AI API 。但我不确定如何使用 SSE 将结果流式传输到客户端,而不是作为单个响应。
我当前的代码如下所示:
func postChatStreamHandler(_ req: Request) throws -> EventLoopFuture<Response> {
let openAI = OpenAI(configuration: configuration)
let promise = req.eventLoop.makePromise(of: Data.self)
let query = ChatQuery(model: .gpt4, messages: messages)
openAI.chatsStream(query: query) { partialResult in
switch partialResult {
case .success(let result):
if let detla = result.choices.first?.delta,
let data = try? JSONEncoder().encode(result) {
promise.succeed(data)
}
case .failure(let error):
...
}
} completion: { error in
...
}
return promise.futureResult.map …Run Code Online (Sandbox Code Playgroud) 我正在尝试在过去没有问题的 Vapor/Fluent 应用程序上运行快速命令。我正在运行swift run App migrate,它通常会更新任何迁移。但它抛出了标题中的错误。
我查看了包文件,其中有:
targets: [
.target(
name: "App",
dependencies: [
.product(name: "Vapor", package: "vapor"),
.product(name: "FluentPostgresDriver", package: "fluent-postgres-driver"),
.product(name: "Fluent", package: "fluent"),
.product(name: "Leaf", package: "leaf"),
// .product(name: "SendGrid", package: "sendgrid"),
],
swiftSettings: [
// Enable better optimizations when building in Release configuration. -- Despite the use of
// the `.unsafeFlags` construct required by SwiftPM, this flag is recommended for Release
// builds. See <https://github.com/swift-server/guides#building-for-production> for details.
.unsafeFlags(["-cross-module-optimization"], .when(configuration: .release))
]
),
.target(name: "Run", …Run Code Online (Sandbox Code Playgroud) 我在Google Cloud Platform上设置了一个Ubuntu实例,并在其上安装了Swift-3和Vapor.然后我尝试使用vapor build命令构建Vapor应用程序并成功完成.然后我运行vapor run应用程序文件夹,它成功启动服务器,控制台说服务在本地主机上可用,0.0.0.0:8080.
但是当我在浏览器窗口中输入我的VM的静态IP时,我无法看到我应该看到的蒸汽页面.相反,我得到一个connection refused错误.
我有一个安装了Apache2,Swift 3.1.1和Vapor的VPS(Ubuntu 14.04).我希望通过HTTPS协议(例如,在端口8443上)接收客户端对我的Vapor-Built-Service的请求.我没有找到任何新手助手文件,所以请帮助我.
谢谢.
我是个蒸气初学者,我选择从Vapor 3-rc开始,因为它似乎破坏了Vaport 2的更改。不幸的是,目前没有完整的文档。
我目前正在尝试从Postman上传一个简单的txt文件到我的Vapor 3本地服务器。
这是我的路线
let uploadController = FileUploadController()
router.post("uploadtxt", use: uploadController.uploadTXT)
Run Code Online (Sandbox Code Playgroud)
和我的控制器
final class FileUploadController {
func uploadTXT(_ req: Request) throws -> Future<String> {
return try req.content.decode(MultipartForm.self).map(to: String.self, { form in
let file = try form.getFile(named: "txtfile")
return file.filename ?? "no-file"
})
}
}
Run Code Online (Sandbox Code Playgroud)
首先,通过执行Postman请求,服务器将返回:
{"error":true,"reason":"There is no configured decoder for multipart\/form-data; boundary=...}
Run Code Online (Sandbox Code Playgroud)
通过调查源代码和有关此的有限文档,似乎我应该声明一个解码器来支持多部分传入的请求。
所以我做了:
var contentConfig = ContentConfig.default()
let decoder = FormURLDecoder()
contentConfig.use(decoder: decoder, for: .multipart)
services.register(contentConfig)
Run Code Online (Sandbox Code Playgroud)
我FormURLDecoder之所以使用它,是因为它似乎是我所需要的最接近的类。BodyDecoder
现在infite-环插入func decode<T>(_ type: …
这可能是一堆蠕虫,我会尽力描述这个问题.我们有一个长期运行的数据处理工作.我们的行动数据库会在夜间添加,并处理未完成的操作.处理夜间行动大约需要15分钟.在Vapor 2中,我们使用了大量的原始查询来创建PostgreSQL游标并循环遍历它直到它为空.
目前,我们通过命令行参数运行处理.将来我们希望它作为主服务器的一部分运行,以便在执行处理时检查进度.
func run(using context: CommandContext) throws -> Future<Void> {
let table = "\"RecRegAction\""
let cursorName = "\"action_cursor\""
let chunkSize = 10_000
return context.container.withNewConnection(to: .psql) { connection in
return PostgreSQLDatabase.transactionExecute({ connection -> Future<Int> in
return connection.simpleQuery("DECLARE \(cursorName) CURSOR FOR SELECT * FROM \(table)").map { result in
var totalResults = 0
var finished : Bool = false
while !finished {
let results = try connection.raw("FETCH \(chunkSize) FROM \(cursorName)").all(decoding: RecRegAction.self).wait()
if results.count > 0 {
totalResults += results.count
print(totalResults)
// Obviously …Run Code Online (Sandbox Code Playgroud) 我正在使用Vapor 3并链接到FoundationDB数据库,因此我不使用Fluent.我有一个搜索记录的方法,但如果它没有返回记录,它会明显崩溃(因为我强制解包该值).
我想保护数据库中的读数,如果没有找到记录则返回响应.然而,这将不是未来预期的记录.我在想我应该返回一个不同的响应,但我不确定如何更改预期的结果.
//creates a specific country
func getCountry( req: Request) throws -> Future<Country> {
// get Country name from get parameter string
let countryString = try req.parameters.next(String.self)
// get record from Database. This could fail and so needs to be guarded. What response should be returned as the Future requires a Country datatype?
let record = FDBConnector().getRecord(path: Subspace("iVendor").subspace(["Countries", countryString]))
let newCountry = try JSONDecoder().decode(Country.self, from: record!)
// return Country Struct
return Future.map(on: req) {return newCountry }
}
Run Code Online (Sandbox Code Playgroud) 在Vapor 2中,您可以执行以下操作:
let query = <some fluent query object>
logger?.debug(query)
Run Code Online (Sandbox Code Playgroud)
它将打印出完整的SQL语句,但现在在Vapor 3中看不到任何有关如何执行此操作的文档。
如何查看我正在生成什么SQL QueryBuilder?
我正在努力了解如何执行对已获取对象的批量保存并将它们存储到数据库中.将对象存储到数据库后,我想返回查询结果.我无法理解如何使用EventLoopFuture执行此操作,因为当我调用时,.wait()我收到错误消息:
前提条件失败:BUG DETECTED:在EventLoop上不能调用wait().
作为我的问题的一个例子:
这是我到目前为止所得到的,但它给了我错误:
func flights(on conn: DatabaseConnectable, customerName: String, flightType: FlightType) throws -> Future<[Flight]> {
return Airport.query(on: conn).filter(\.customerName == customerName).first().flatMap(to: [Flight].self) { airport in
guard let airport = airport else {
throw Abort(.notFound)
}
guard let airportId = airport.id else {
throw Abort(.internalServerError)
}
// Update items for customer
let fetcher: AirportManaging?
switch customerName.lowercased() {
case "coolCustomer":
fetcher = StoreOneFetcher()
default:
fetcher = nil
debugPrint("Unhandled customer to fetch from!")
// Do nothing
} …Run Code Online (Sandbox Code Playgroud) vapor ×10
swift ×8
event-loop ×1
future ×1
hosting ×1
ios ×1
nstask ×1
openai-api ×1
postgresql ×1
swift-nio ×1
ubuntu-14.04 ×1
vapor-fluent ×1
vps ×1
xcode ×1