我们正在开发一个中间件SDK,用C++和Java作为库/ DLL,例如,由游戏开发者,动画软件开发人员,Avatar开发人员来增强他们的产品.
我想知道的是:开发这些类型的API是否有标准的"最佳实践"?
我在考虑可用性,可读性,效率等方面.
我一直在尝试对我的CherryPy Web服务器进行性能分析,但是该文档缺少如何设置的详细信息。我了解我应该能够cherrypy.lib.profiler用作中间件来安装我的初始服务器。现在,我有如下代码:
server_app = ServerClass()
cherrypy.tree.mount(server_app, '/', '/path/to/config/file.cfg')
cherrypy.engine.start()
cherrypy.engine.block()
Run Code Online (Sandbox Code Playgroud)
我想挂载性能分析中间件,似乎需要以下内容:
from cherrypy.lib import profiler
server_app = ServerClass()
server_cpapp = cherrypy.Application(server_app, '/', '/path/to/config/file.cfg')
server_profile_cpapp = profiler.make_app(server_cpapp, '/home/ken/tmp/cprofile', True)
#cherrypy.tree.mount(server_profile_cpapp)
cherrypy.tree.graft(server_profile_cpapp)
cherrypy.engine.start()
cherrypy.engine.block()
Run Code Online (Sandbox Code Playgroud)
出于某种原因,cherrypy.tree.mount它不起作用,但是,如果我使用cherrypy.tree.graft全部,似乎一切正常(我可以像往常一样向服务器发出请求)
但是,上面的代码cp_0001.prof在下面生成一个文件/home/ken/tmp/cprofile,我不确定如何解释它。我尝试使用pyprof2calltree将数据读取到KCacheGrind中,但是遇到解析错误。我正在做的事情看起来是否正确,如果可以,我该如何解释输出文件?
我想用机架中间件打印模板的主体.下面是我的设置......
#config/initializers/response_timer.rb
class ResponseTimer
def initialize(app)
@app = app
end
def call(env)
status, headers, response = @app.call(env)
[status, headers, response.body]
end
end
#application.rb file
config.middleware.use "ResponseTimer"
Run Code Online (Sandbox Code Playgroud)
当我提出请求domainname/students /我收到以下错误.
undefined method `each' for #<String:0xd69a2e0>
Run Code Online (Sandbox Code Playgroud)
请帮助.
我正在寻找最简单,最高效的方法来制作用于管理项目的多租户express.js应用程序.
阅读几篇博客和文章,我发现,对于我的应用程序,每个租户架构都有一个数据库会很好.
我的第一次尝试是使用子域来检测租户,然后将子域映射到mongodb数据库.
我想出了这个快速的中间件
var mongoose = require('mongoose');
var debug = require('debug')('app:middleware:mongooseInstance');
var conns [];
function mongooseInstance (req, res, next) {
var sub = req.sub = req.subdomains[0] || 'app';
// if the connection is cached on the array, reuse it
if (conns[sub]) {
debug('reusing connection', sub, '...');
req.db = conns[sub];
} else {
debug('creating new connection to', sub, '...');
conns[sub] = mongoose.createConnection('mongodb://localhost:27017/' + sub);
req.db = conns[sub];
}
next();
}
module.exports = mongooseInstance;
Run Code Online (Sandbox Code Playgroud)
然后我在另一个中间件中注册模型:
var fs = require('fs');
var debug …Run Code Online (Sandbox Code Playgroud) 我正在使用Julien Schmidt的GoLang路由器,并尝试让它与Alice合作来连接中间件.我收到这个错误:
不能使用commonHandlers.ThenFunc(final)(类型http.Handler)作为路由器的参数httprouter.Handle.GET
而且我不太清楚为什么.
我的代码是:
package main
import (
"log"
"net/http"
"github.com/julienschmidt/httprouter"
"github.com/justinas/alice"
"gopkg.in/mgo.v2"
//"gopkg.in/mgo.v2/bson"
)
func middlewareOne(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("Executing middlewareOne")
next.ServeHTTP(w, r)
log.Println("Executing middlewareOne again")
})
}
func middlewareTwo(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("Executing middlewareTwo")
if r.URL.Path != "/" {
return
}
next.ServeHTTP(w, r)
log.Println("Executing middlewareTwo again")
})
}
func final(w http.ResponseWriter, r *http.Request) {
log.Println("Executing finalHandler")
w.Write([]byte("OK"))
}
func main() {
session, err := mgo.Dial("conn-string") …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用快速中间件来实现一些缓存,这似乎很好用,但是我陷入了无限循环的麻烦。
在我的路由器中,我必须遵循以下路线:
router.get('/test', [middleware.cache.cache('1 day', true), controllers.test]);
Run Code Online (Sandbox Code Playgroud)
middleware.cache.cache看起来像这样:
module.exports.cache = function(time, global) {
// Do some stuff with the time here
return function cache(req, res, next) {
// Keep a copy of the actual send method
res._send = res.send;
// Overwrite the res.send function
res.send = function(obj) {
console.log('[' + res.statusCode + '] Cache: ' + redisKey);
// Get the key from redis
redis.get(redisKey)
.then(function(result) {
result = JSON.parse(result);
if(!_.isNull(result)) {
console.log('Expired cache found');
// Send initial object
return res._send(obj); …Run Code Online (Sandbox Code Playgroud) 我们怎样才能app.use()在我们调用它时添加中间件并使用该中间件.目前我有这个代码:
function ensureUser(req,res,next){
if(req.isAuthenticated()) next();
else res.send(false);
}
app.get('/anything', ensureUser, function(req,res){
// some code
})
Run Code Online (Sandbox Code Playgroud)
我正在尝试将ensureUser添加到我有路由的所有文件中.我带来了一个解决方案,将该文件添加到一个文件中,并在我有路由的每个文件中要求该文件.有没有办法将该函数添加到app.use或app.all类似的东西,因为我不必在每个文件中包含该函数.
我试图使用中间件缓存整个响应
我遵循的步骤
生成两个中间件
在BeforeCacheMiddleware中:
public function handle($request, Closure $next)
{
$key = $request->url();
if(Cache::has($key)) return Cache::get($key);
return $next($request);
}
Run Code Online (Sandbox Code Playgroud)
在AfterCacheMiddleware中
public function handle ($request, Closure $next)
{
$response = $next($request);
$key = $request->url();
if (!Cache::has($key)) Cache::put($key, $response->getContent(), 60);
return $response;
}
Run Code Online (Sandbox Code Playgroud)
在kernal.php的$ routeMiddleware数组中注册的中间件
'cacheafter' => 'App\Http\Middleware\AfterCacheMiddleware',
'cachebefore' => 'App\Http\Middleware\BeforeCacheMiddleware',
Run Code Online (Sandbox Code Playgroud)
在routes.php中,我正在调用这样的虚拟路线
Route::get('middle', ['middleware' => 'cachebefore', 'cacheafter', function()
{
echo "From route";
}]);
Run Code Online (Sandbox Code Playgroud)
问题:
只有缓存才能调用中间件.cacheafter根本没有被调用
任何人都可以建议我在这里缺少什么?
我愿意将所有http请求保存到数据库(request_method代表db字段)并将它们打印到页面(例如,最后10个请求)但是我遇到以下问题:异常值:'WSGIRequest'对象没有属性'Meta'.
models.py
from django.db import models
class HttpRequest(models.Model):
time = models.DateTimeField(auto_now=True, auto_now_add=False)
request_method = models.CharField(max_length=20)
Run Code Online (Sandbox Code Playgroud)
middleware.py
from .models import HttpRequest
class FirstMiddleware(object):
def process_request(self, request):
data = HttpRequest(request_method=request.Meta['REQUEST_METHOD'])
data.save()
Run Code Online (Sandbox Code Playgroud)
views.py
from django.shortcuts import render
def view_requests(request):
request_list = HttpRequest.objects.all()[:10]
return render(request, 'apps/hello/request_list', {'list': request_list})
Run Code Online (Sandbox Code Playgroud)
在处理middleware.py文件期间会出现此问题(这就是为什么我不确定这里是否需要view.py,但为什么不是:))由于我是django的完全初学者,因此修复它是一个很大的挑战我自己,虽然任务似乎很容易.对你的见解会很高兴.
在Express中间件中,应该采用3个参数:request,response,next.但是,在我从书中复制的代码中的第二个中间件,但只使用请求,响应.这是什么原因?接下来是可选的?
var express = require("express");
var http = require("http");
var app = express();
app.use(function(request, response, next) {
console.log("In comes a " + request.method + " to " + request.url);
next();
});
app.use(function(request, response) {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Hello, world!");
});
http.createServer(app).listen(3000);
Run Code Online (Sandbox Code Playgroud)