我从一个Java REST背景来Python上Google App Engine's.我需要一些使用webapp2路径参数的帮助.下面是Java如何读取请求的示例.有人请将代码翻译成python如何阅读它webapp2?
// URL: my_dogs/user_id/{user_id}/dog_name/{a_name}/breed/{breed}/{weight}
@Path("my_dogs/user_id/{user_id}/dog_name/{a_name}/breed/{breed}/{weight}")
public Response getMyDog(
@PathParam("user_id") Integer id,
@PathParam("a_name") String name,
@PathParam("breed") String breed,
@PathParam("weight") String weight
){
//the variables are: id, name, breed, weight.
///use them somehow
}
Run Code Online (Sandbox Code Playgroud)
我已经走了过来例子在谷歌(https://developers.google.com/appengine/docs/python/gettingstartedpython27/usingwebapp).但我不知道如何扩展简单
app = webapp2.WSGIApplication([('/', MainPage),
('/sign', Guestbook)],
debug=True)
Run Code Online (Sandbox Code Playgroud) 我已经实施了休息服务.
我试图在过滤器中获取请求的路径参数.
我的要求是
/api/test/{id1}/{status}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException
{
//Way to get the path parameters id1 and status
}
Run Code Online (Sandbox Code Playgroud) 我试图在REST URI中接收一个String列表作为逗号分隔值(示例:
http://localhost:8080/com.vogella.jersey.first/rest/todo/test/1/abc,test
Run Code Online (Sandbox Code Playgroud)
,其中abc和test是传入的逗号分隔值).
目前我将此值作为字符串,然后将其拆分以获取各个值.当前代码:
@Path("/todo")
public class TodoResource {
// This method is called if XMLis request
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("/test/{id: .*}/{name: .*}")
public Todo getXML(@PathParam("id") String id,
@PathParam("name") String name) {
Todo todo = new Todo();
todo.setSummary("This is my first todo, id received is : " + id
+ "name is : " + Arrays.asList(name.split("\\s*,\\s*")));
todo.setDescription("This is my first todo");
TodoTest todoTest = new TodoTest();
todoTest.setDescription("abc");
todoTest.setSummary("xyz");
todo.setTodoTest(todoTest);
return todo;
}
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来实现同样的目标?
我的功能看起来像这样:
@PUT
@Path("property/{uuid}/{key}/{value}")
@Produces("application/xml")
public Map<String,ValueEntity> updateProperty(@Context HttpServletRequest request,
@PathParam("key") String key,
@PathParam("value") String value,
@PathParam("uuid") String uuid) throws Exception {
...
}
Run Code Online (Sandbox Code Playgroud)
我必须修改它,因此它接受来自REST调用的无限(或许多)键值对列表,例如
@Path("property/{uuid}/{key1}/{value1}/{key2}/{value2}/{key3}/{value3}/...")
Run Code Online (Sandbox Code Playgroud)
是否可以将它们存储在数组或列表中,所以我没有列出几十个@PathParams和参数,以避免这种情况:
@PathParam("key1") String key1,
@PathParam("key2") String key2,
@PathParam("key3") String key3,
Run Code Online (Sandbox Code Playgroud) 我尝试通过GET将参数传递给REST方法.
@GET
@Path("{id}")
public Response getUser(@PathParam("id") String id) {
Query qry = em.createQuery("from User c WHERE id = :user_id");
qry.setParameter("user_id", id);
List<User> results = qry.getResultList();
if(results.size() > 0) {
return Response.ok(results.get(0),MediaType.APPLICATION_JSON_TYPE).build();
} else {
return Response.serverError().status(Response.Status.NOT_FOUND).build();
}
}
Run Code Online (Sandbox Code Playgroud)
如果我通过Rest Client调用它:
client = ClientBuilder.newClient();
Response response = client.target(TestPortProvider.generateURL("/user")+"/abc").request().get(Response.class);
Run Code Online (Sandbox Code Playgroud)
然后调用该方法,但参数为空.如果我"abc"从GET url中删除该方法,则不会调用该方法.此外,如果我删除@Path("{id}")它也不起作用.似乎有一个参数,但它没有任何理由是空的.也许有人可以帮我解决问题.
亲切的问候
给定WebSocket端点如下.
@ServerEndpoint(value = "/Push/CartPush/{token}")
public final class CartPush {
// ...
}
Run Code Online (Sandbox Code Playgroud)
端点能够接受路径参数{token}.但是,path参数是可选的,它是在Java Script中在运行时动态确定的.在JavaScript中跳过此参数,如下所示404.
var ws = new WebSocket("wss://localhost:8443/ContextPath/Push/CartPush");
Run Code Online (Sandbox Code Playgroud)
WebSocket连接
'wss://localhost:8443/ContextPath/Push/CartPush'失败:WebSocket握手期间出错:意外响应代码:404
它使得令牌值必须如下.
var token = "token value";
var ws = new WebSocket("wss://localhost:8443/ContextPath/Push/CartPush" + "/" + token);
Run Code Online (Sandbox Code Playgroud)
为了排除除GET和之外的所有不需要的HTTP方法POST,我使用以下限制或约束以及使用适当的URL模式和角色映射的Servlet安全性约束web.xml.
<security-constraint>
<web-resource-collection>
<web-resource-name>Disable unneeded HTTP methods by 403</web-resource-name>
<url-pattern>/Public/*</url-pattern>
<url-pattern>/Push/*</url-pattern>
<url-pattern>/javax.faces.resource/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
</security-constraint>
<deny-uncovered-http-methods/> <!-- Requires Servlet 3.1 -->
Run Code Online (Sandbox Code Playgroud)
如何使给定的路径参数可选?
正在使用的服务器是WildFly 10.0.0 final/Java EE 7.
我正在尝试使用Jersey使用@PathParam,但它总是将其视为null.
这里的方法:URL是http://localhost:8080/GiftRegistryAPI/api/v2/inventory/david与/v2/inventory处于一流水平
package com.omar.rest.inventory;
import javax.websocket.server.PathParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import org.codehaus.jettison.json.JSONArray;
import com.omar.rest.util.*;
@Path("/v2/inventory")
public class V2_Inventory {
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response returnHostRegistries(@QueryParam("hostId") int hostId) throws Exception {
String returnString = null;
JSONArray jsonArray = new JSONArray();
try {
// A host ID of 0 indicates a null parameter, there will never be a host with an ID of 0
if (hostId == …Run Code Online (Sandbox Code Playgroud) 我有一个端点:
@Path("/products")
@Produces({ MediaType.APPLICATION_JSON })
public interface Products {
@PUT
@Path("/{productId}")
....
}
Run Code Online (Sandbox Code Playgroud)
我为这个服务实现了一个 jax-rs 客户端,并将它导入到我从中调用它的另一个服务中。
所以我从我的第二个服务中调用客户端如下
public String updateProduct(String productId){
..
return client.target(this.getBaseUrl()).path("products/").path(productId).request(MediaType.APPLICATION_JSON_TYPE).put(Entity.json(""), String.class);
}
Run Code Online (Sandbox Code Playgroud)
如果我有一个带有斜杠的产品,上面写着“控制/注册应用程序”,该服务似乎不太好。我确实在调用服务之前对 productId 进行了编码,然后在收到后对其进行解码。但这似乎不起作用,我找不到 404。有任何想法吗?提前致谢
java ×5
rest ×5
jax-rs ×3
jersey ×3
servlets ×2
web-services ×2
endpoint ×1
java-ee ×1
javax.ws.rs ×1
python-2.7 ×1
webapp2 ×1
websocket ×1