I have a TemplateView that returns a TemplateResponse object in a process_template_response middle-ware, but the later is never triggered.
When i change the middleware method in process_response and preform render() on the TemplateResponse, the middle-ware method is triggered and the page is render.
Which steps do i need preform to render a view in a process_template_response?
View:
class PageView(TemplateView):
template_name = 'flatpages/default.html'
def get(self, request, *args, **kwargs):
url = kwargs['url']
if not url.endswith('/') and settings.APPEND_SLASH:
return HttpResponseRedirect(url + '/')
if not url.startswith('/'):
url = url + '/'
kwargs.update({'url': url})
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
def get_context_data(self, **kwargs):
url = kwargs.pop('url')
context = super(PageView, self).get_context_data(**kwargs)
page = get_object_or_404(ParentPage, url__exact=url, sites__id__exact=settings.SITE_ID)
context.update({'flatpage': page})
return context
class PageFallbackMiddleware(object):
def process_template_response(self, request, response):
print 'Triggered'
if response.status_code != 404:
return response
try:
return PageView.as_view()(request, url=request.path_info)
except Http404:
return response
except:
if settings.DEBUG:
raise
return response
I think you may have to return a TemplateResponse or similar for the middleware to route the view to another template, returning the response parameter or another HTTPResponse instance is a no-op.
Related
I am working on creating a asyncio.Future callback for requests whereby I store the body of the response in json format and return this result. I initially wanted to create a callback on the function on_response, however I was not certain how to implement this. Therefore, I decided to include option parameters to add into the callable such as url.
For example:
import asyncio
from functools import partial as func
import requests
import json
url = "https://www.scrapethissite.com/pages/ajax-javascript/?ajax=true&year=2015"
class schedulerLoop(asyncio.Future):
def __init__(self, url):
super(schedulerLoop, self).__init__()
self._url = url
#staticmethod
def unwrapper(funct):
return funct()
def _future(self, *args):
return self.add_done_callback(func(self.unwrapper, *args))
async def on_response(self):
if self.done():
obj = await self._future(func(requests.get, self._url))
body = json.loads(obj)
return body
else:
self.exception()
async def main(loop):
await loop.on_response()
loop = schedulerLoop(url)
if __name__ == '__main__':
asyncio.run(main(loop))
I find that I get:
asyncio.exceptions.InvalidStateError: Exception is not set.
Which supposes that on_response the Future is not done, and so we get a False result but there seems be no no Exception neither.
Why its not works ?
def post = new URL(url).openConnection();
post.setRequestMethod("PATCH");
post.setDoOutput(true);
post.setRequestProperty("Content-Type", "application/json");
post.getOutputStream().write(body.getBytes("UTF-8"));
def postRC = post.getResponseCode();
logger.info("Status code = ${postRC}");
returns error = java.net.ProtocolException: Invalid HTTP method: PATCH
old java HttpUrlConnection.setRequestMethod() does not support patch method:
https://docs.oracle.com/javase/10/docs/api/java/net/HttpURLConnection.html#setRequestMethod(java.lang.String)
public void setRequestMethod​(String method) throws ProtocolException
Set the method for the URL request, one of:
GET
POST
HEAD
OPTIONS
PUT
DELETE
TRACE
however there is a trick - in groovy you could set protected property value and there is a property method
https://docs.oracle.com/javase/10/docs/api/java/net/HttpURLConnection.html#method
so you could change the code:
def body = [test:123]
def post = new URL("http://httpbin.org/patch").openConnection();
post.method ="PATCH";
post.setDoOutput(true);
post.setRequestProperty("Content-Type", "application/json");
post.getOutputStream().withWriter("UTF-8"){ it << new groovy.json.JsonBuilder(body) }
def postRC = post.getResponseCode();
println "Status code = ${postRC}"
println post.getInputStream().getText("UTF-8")
I want to wrap the upload part in a common function since it is used in multiple API routes, but how do I do it since it is using async def here.
#app.post("/api/od")
async def image_classification(files: typing.List[fastapi.UploadFile] = fastapi.File(...)):
upload_path = pathlib.Path("upload")#.joinpath(token)
upload_path.mkdir(exist_ok=True)
...
return results
I am using a Grails service closure to perform a async HTTP request to another web application. Using Grails 1.3.9, I am very limited here. The code runs inside a thread. It is called from a scheduled job and from several function calls. The error I get is below:
ERROR:
java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
CODE:
Thread.start {
def http = new HTTPBuilder(grailsApplication?.config?.smsConfig?.smsServiceAddress);
try {
http.request(POST) {
body = bodyRequest;
requestContentType = ContentType.JSON
response.success = { resp ->
println "SUCCESS! ${resp.status}"
def user = RequestContextHolder.currentRequestAttributes().getSession().user
if (user != null) {
if (termin) {
termin.withTransaction {
try {
// do desired action
} catch (e) {
println(e);
}
}
}
}
}
response.failure = { resp ->
println "FAILURE request failed with status ${resp.status}, response body was [${resp.entity.content.text}]"
System.out << resp
}
}
}
//here error is caught
catch (e) {
log.error "Error: " + e;
}
}
I have tried adding this options to web.xml
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
and also this to WebXmlConfig.groovy
listener.add = true
listener.classNames = ["org.springframework.web.context.request.RequestContextListener"]
but both did not help
This is something that isn't well documented or can you send you spirals:
Try this:
/*
* Fix for No thread-bound request found: Are you referring to request attributes
*/
def webRequest = RequestContextHolder.getRequestAttributes()
if(!webRequest) {
def servletContext = ServletContextHolder.getServletContext()
def applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)
webRequest = grails.util.GrailsWebMockUtil.bindMockWebRequest(applicationContext)
}
You will need spring test in your build.gradle
compile 'org.springframework:spring-test:2.5'
There is a grails 2 branch so follow the same class in the other branch if it is grails 2
I am working on SMS send and receive functionality in an MVC3 application. How can I send a response to a URL? Any URL that hits my page should get a response like "ok" or "received".
For example, consider the code below, which is sent from a provider to my site. I need to send a response text like "ok" or received to stringResult. If I can respond to URL with some "success" parameter that would be great.
string stringResult = null;
stringpost ="parameters for url";
objWebRequest = (HttpWebRequest)WebRequest.Create("http://myip/app/action/receivesms?");
objWebRequest.Method = "POST"
if ((objProxy1 != null))
{
objWebRequest.Proxy = objProxy1;
}
objWebRequest.ContentType = "applicationwww-form-urlencoded";
objStreamWriter = new StreamWriter(objWebRequest.GetRequestStream());
objStreamWriter.Write(stringpost);
objStreamWriter.Flush();
objStreamWriter.Close();
objWebResponse = (HttpWebResponse)objWebRequest.GetResponse();
objStreamReader = new StreamReader(objWebResponse.GetResponseStream());
stringResult = objStreamReader.ReadToEnd();
objStreamReader.Close();
return (stringResult);
Just do this in your controller:
public ActionResult YourAction()
{
return Content("OK");
}
Or, if you wanted to use HTTP codes instead of strings, you could do something like:
public ActionResult YourAction()
{
// 204 is the HTTP code for OK with no content
return new HttpStatusCodeResult(204);
}
stringResult = objStreamReader.ReadToEnd();
stringResult in your code recieve server response. this response contains ok or succuessfully sent.
you have to interpret the response and then send your message to the client and you can call this send smsmethod using ajax.
In ajax method call you can show dialog of "OK" or "RECIEVED"