I am trying to build a uri using uri_for and a named Route.
This is my barebones code:
app = webapp2.WSGIApplication([
(r'/screenshot_worker', 'mkt.ScreenshotWorker'),
webapp2.Route(r'/screenshot/<screenshot_key>',
handler='mkt.ScreenshotHandler', name='screenshot')
])
and the handler
class ScreenshotWorker(webapp2.RequestHandler):
def post(self):
d = date.today().strftime('%d%m%Y')
key = ndb.Key('Screenshot', d)
url = self.uri_for('screenshot', screenshot_key=key) #fails
which fails with
KeyError: "Route named 'screenshot' is not defined."
The handler you have defined and built URI is ScreenshotWorker , whereas for the Route named screenshot, the handler mentioned is ScreenshotHandler
It looks like there is an issue with your route definitions. I'm not sure if it's a typo from your code excerpting or not, but the line:
(r'/screenshot_worker', 'mkt.ScreenshotWorker'),
is missing the leading webapp2.Route (which your second definition correctly uses), which may be breaking your entire url map.
Related
Myapp is java springboot microservice deployed in kubernetes. In local it works fine since I do not need proxy and kubernetes.yml, however when I deploy to int environment, I run into "404 page not found" error.
Please advice if there is any other way to call the service endpoint with this path /api/v1/primary-domain/domain-objects?parameter1=645¶meter2=363¶meter3=2023-02-01
Why is it not able to find the resource? Are there any options to make this work still with same naming pattern for path?
application.properties
server.servlet.context-path=/api/v1/primary-domain/domain-objects management.endpoints.web.base-path=/ management.endpoint.health.show-details=always management.endpoints.web.path-mapping.health=health
#API Registry
springdoc.api-docs.path=/doc
controller:
`#GetMapping(value="", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<DomainObjectsMsResponseDTO>> getDomainObjects(
#RequestParam(name = "parameter1", required = false) String parameter1,
#RequestParam(name = "parameter2", required = false) String parameter2,
#RequestParam(name = "parameter3", required = false) String parameter3,
) throws Exception{..}`
The path variable in proxy is /v1/primary-domain/domain-objects
proxy.yml
.
.
spec: path: /v1/primary-domain/domain-objects target: /api/v1/primary-domain/domain-objects
.
.
Due to the architecture direction the path for health, doc and actual service endpoint should follow certain naming convention, hence running this issue.
If I use proxy.yml path variable v1/primary-domain and getMapping( value="/domain-objects"..) then it works fine but the domain-objects/doc endpoint returns sever array with url: api/v1/primary-domain, which is not what I want. Since under primary-domain multiple microservices will be created which will be in their own gitRepos and they will path like /primary-domain/points and /primary-domain/positions
I tried getMapping( value="/"..) and removing value variable entirely from getMapping, but still getting same error
I tried changing the Label variables, path target and paths in kube and proxy and matched the app.proeprties and controller to go with it. However with every approach one thing gets broken. None of the approach satisfies endpoint, health endpoint, doc endpoint( open api)
I've got a Django app with Tastypie, and mainly BackBone client side. One of my models has a few ImageFields. Here is a similar setup to help me explain the issue.
settings.py
MEDIA_URL = "/media/"
models.py
class Foo(models.model):
bar = models.ImageField()
baz = models.CharField()
api.py
class FooResource(ModelResource):
class Meta:
queryset=models.Foo.objects.all()
resource_name = "foo"
authorization = Authorization()
When I make a GET request to the API, it appends the MEDIA_URL to the file names to return the URI where a bar can be accessed. However, when I change the value of baz on a row, and then make a PUT request with that, it also changes the value for a bar to the URI. This means that the next time I GET the row, it appends the MEDIA_URL again, breaking the system and appending it for each successive GET and PUT. I end up with values for bar in the DB that look like.
/media/media/media/bar.jpg
I think I should fix this by overriding a method in my ModelResource, so that when there is a PUT request, it recognizes that it's getting either a URI or a real file, and alters its behavior in some way.
Is this the correct fix? Could you provide some implementation details of a fix?
I found the answer. Tastypie is well designed, similarly to Django. Unfortunately I was not familiar with the terminology so when I read the docs I didn't understand. You can easily modify behavior of the API at many levels. Here is my new API definition, which fixed the issue.
api.py
class FooResource(ModelResource):
class Meta:
queryset=models.Foo.objects.all()
resource_name = "foo"
authorization = Authorization()
def hydrate_bar(bundle):
bundle["bar"] = bundle["bar"].strip(MEDIA_URL)
return bundle
I should add that this only works for me because I exclusively POST my image files individually with a post_detail method which doesn't call this method. If I was to POST or PUT image files as part of the entire row, I expect this might raise an error if that isn't considered.
I am building a UI into a JAR for Spring Server. I have a bunch of Angular JS pages. I want to pass in a command line argument to my jar that tells it where the API server is like so:
java -jar application.jar --api=http://ip:9000
So my application.properties file has:
url=${api:http://localhost:9000}
The way I am currently doing is it just having a hardocoded js config file and on each of my .html pages:
<script src="../js/appName/config.angular.js"></script>
Which contains:
var configData = {
url:"http://localhost:9000"
};
And called in each file:
$scope.apiUrl = configData.url;
How do I tap into the applications.properties file that I can override with my JAR command line parameter during runtime vs. the way it has been coded now.
When you pass a value from command line and the same property name is present in properties file then spring boot overrides the value from command line. So to achieve what you want do something like this
In application.properties
#this is default value
app.url=localhost:8080
Create a class to map the properties value or you can use existing class or something else based on your project structure.
#Component
public class Sample {
#Value("${app.url}")
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Now when your execute a jar with argument --app.url="someserver:9090" the value will be overriden and you can use this value anywhere.
Note it will also work if you try to access the properties value directly in jsp using expression.
Try it, it works. I have used the same thing in my latest project which is a composite microservices and each component need each others url.
[Edit]
Reference : http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
Am I getting it right: The client part is delivered by the application? So the part of the last sentence 'during runtime' has more the meaning of 'bootstrap/initial loading', right? One (old school) approach is to provide the entry html (e.g. index.html) through the application (a simple template engine) and provide the needed information with a setter in a JS config object:
// pseudo js code with thymeleaf
<script th:inline="javascript">
/*<![CDATA[*/
myConfig.url = [[${#httpServletRequest.remoteHost}]];
/*]]>*/
</script>
This is just a sample that will only set the remote host name but I think you get the idea.
Side note: I still don't really get why do you have to set this. If the application contains the client code, why do you work with absolute URLs for remote calls? (Disclaimer: I have only experience in Angular(2) and not with AngularJS)
I'm a django newbie. Here is my problem.... My main urls.py has a rule for checking published section to published app, like this:
(r'^(published/)$', include('published.urls')),
My published app urls.py is like:
urlpatterns = patterns('published.views',
# Examples:
(r'^$', 'index',),
(r'^(?P<id>\d+)/$', 'article'),
)
I'm trying to fetch a url like this
http://localhost:8000/published/2/
Problem is its showing a 404 error. Just to clarify my view is like this:
def article(request):
try:
p = Published.objects.get(pk = id)
except Published.DoesNotExist:
raise Http404
return render_to_response('published/inner.html', {'pubs': p}, context_instance = RequestContext(request))
Can anyone tell me what is the problem?
You should try removing the $ from the end of r'^(published/)$'. If it still does not work, try removing the ^ from the beginning of r'^(?P<id>\d+)/$'. Since $ matches the end of a string, the regex fails to match when there is a character after the first /.
I am having problems getting the logout link work in GAE (Python).
This is the page I am looking at.
In my template, I create a link
<p>Logout</p>
But when I click on it I get "broken link" message from Chrome. The url for the link looks like this:
http://localhost:8085/users.create_logout_url(
My questions:
Can anybody explain how this works in general?
What is the correct url for the dev server?
What is the correct url for the app server?
What is the ("/") in the logout url?
Thanks.
EDIT
This link works; but I don't know why:
<p>Logout</p>
What sort of templates are you using? It's clear from the output that you're not escaping your code correctly.
Seems to me that you want to do this instead:
self.response.out.write("This is the url: %s", users.create_logout_url("/"))
You could also pass it to your template, using GAEs implemented django templates.
from google.appengine.ext.webapp import template
...
...
(inside your request handler)
class Empty: pass
data = Empty()
data.logout = users.create_logout_url("/")
self.response.out.write(template.render(my_tmpl, {'data': data})
A useful approach is to add all sorts of info to a BaseRequestHandler and then use this as base class for all of your other request handler classes.
from google.appengine.ext import webapp
...
class BaseRequestHandler(webapp.RequestHandler):
def __init__(self):
webapp.RequestHandler.__init__(self) # extend the base class
class Empty: pass
data = Empty()
data.foo = "bar"
Then your new classes will have access to all the data you provided in the base class.
class OtherHandler(BaseRequestHandler):
def get(self):
self.response.out.write("This is foo: %s" % self.data.foo) # passes str "bar"
Hope it helps.
A.
Hi following more or less what this article is showing for the user account stuff. In gwt I store server side the logout/login url and I pass them to the client
http://www.dev-articles.com/article/App-Engine-User-Services-in-JSP-3002