dynamic import from literal string instead of path in ES6 - ecmascript-6

is it possible to import from a js string?
import(`alert("Hello")`);
which gives us more control over http fetching, like loading from protected url with access token.

Related

Yii2 HttpClient: Access Request instance from Response instance

Using yii2-httpclient, what is the correct way to access the corresponding yii\httpclient\Request instance from the resulting yii\httpclient\Response object?
I am trying to write a custom XML parser which needs to know what URL it is parsing. It does not seem to be possible to access the original Request (through which I could get the URL) from a parser instance (only the Response).
I have considered utilizing yii\httpclient\Client::EVENT_AFTER_SEND to copy the request into a variable, but that would not be thread-safe, so I need a better solution.
If your parser needs to know URL of request to parse response, it is probably not a parser and you're overusing parser API and ParserInterface. I suggest to create some component which will wrap and hide all request-response-parser logic. Then you will be able to implement custom parser and call it manually:
public function get($url) {
$client = new Client();
$response = $client->createRequest()
->setUrl($url)
->send();
return (new MyParser($url, $response))->getContent();
}

How to get JSON data in an Odoo controller?

I am trying to send some JSON data to an Odoo controller, but when I send the request, I always get 404 as response.
This is the code of my controller:
import openerp.http as http
import logging
_logger = logging.getLogger(__name__)
class Controller(http.Controller):
#http.route('/test/result', type='json', auth='public')
def index(self, **args):
_logger.info('The controller is called.')
return '{"response": "OK"}'
Now, I type the URL (http://localhost:8069/test/result) on the browser to check if it is available, and I get function index at 0x7f04a28>, /test/result: Function declared as capable of handling request of type 'json' but called with a request of type 'http'. This way I know that the controller is listening at that URL and is expecting JSON data.
So I open a Python console and type:
import json
import requests
data = {'test': 'Hello'}
data_json = json.dumps(data)
r = requests.get('http://localhost:8069/test/result', data=data_json)
When I print r in the console, it returns <Response [404]>, and I cannot see any message in the log (I was expecting The controller is called.).
There is a similar question here, but it is not exactly the same case:
OpenERP #http.route('demo_json', type="json") URL not displaying JSON Data
Can anyone help me? What am I doing wrong?
I have just solved the problem.
Firstly, as #techsavvy told, I had to modify the decorator, to write type='http' instead of type='json'.
And after that, the request from the console returned a 404 error because it did not know which database it was sending data to. In localhost:8069 I had more than one database. So I tried to have only one at that port. And that is, now it works great!
To manage that without removing any of the other databases, I have just modified the config file to change the parameter db_filter and put there a regular expression which only included my current database.
I have just gone through your issue and I noticed that you have written JSON route which is call from javascript. if you want to call it from browser url hit then you have to define router with type="http" and auth="public" argument in route:
#http.route('/', type='http', auth="public", website=True)

Google Cloud Endpoints allowed method's return types

I'm developing a REST API using Cloud Endpoints. I know that as per the documentation each API method should return an entity that is then automatically converted to a valid JSON string.
However, I'm dealing with an authentication library that in some cases returns a JSON which should be passed back to the client as a response.
Sticking with the default approach, meaning returning an entity, would still be possible, but it would involve a number of obnoxious intermediate steps, like parsing the JSON and filling the right fields of the entity to be returned according to the JSON content.
I was wondering if there is a more straightforward way to instruct the API to directly return the JSON string, instead of converting it to an entity just to have it translated back to the source JSON.
One thing that probably may help you.
Suppose you have a RPC response class as
from protorpc import messages
from protorpc import message_types
from protorpc import remote
class ApiResponse(message.Messages):
response = messages.StringField(1, required = True)
You can return your JSON in response field by using JSON module. First of all import json in your endpoints api
import json
Suppose your response is
json_response = [{'name': 'Jack', 'age':12}, {'name': 'Joe', 'age':13}]
In your response to this api you can do this:-
return ApiResponse(response = json.dumps({'data': json_response}))
json.dumps() converts your dictionary object into JSON string that can be passed to response of ApiResponse class.
After you receive response in client side(javascript), you can simply parse it to JSON using
JSON.parse(response)

How can I parse a URL using JSON in Python?

I have a URL on my Raspberry Pi device server. How can I parse it?
I have used the urllib2 module to get the contents of the URL from server.
I want to use JSON for parsing the url.
so if i understad properly , you have a json file with a URL that you want to pass to your python module
used this a while back
import json
with open('yourjasonfilewithurl.jason') as json_data_file:
data = json.load(json_data_file)
The use the data function like this, the below is dependant on the number of elements you have set up in your json config file
myurl = (data["details"][0]["url"])
hope this helps

why use http.route() method use type="json" in openerp

above code from the website_mail module controller file email_designer.py file
class WebsiteEmailDesigner(http.Controller):
#http.route('/website_mail/email_designer/<model("email.template"):template>/', type='http', auth="user", website=True, multilang=True)
def index(self, template, **kw):
values = {
'template': template,
}
return request.website.render("website_mail.designer_index", values)
#http.route(['/website_mail/snippets'], type='json', auth="user", website=True)
def snippets(self):
return request.website._render('website_mail.email_designer_snippets')
which situation we are using type="json" and type="http" and why..??
Basically type="json" is used to pass data from controller where as type="html" is for responding over http request.
For example from your above code:
the url "/website_mail/email_designer//" will respond towards any particular http request and route to its web page where as the url "/website_mail/snippets" will just pass json data to its rendered template but there is no physical webpage related to this url.
Methods that received JSON can be defined by passing 'json' to the type argument of http.route(). The OpenERP Javascript client can contact these methods using the JSON-RPC protocol. JSON methods must return JSON. Like the HTTP methods they receive arguments as named parameters (except these arguments are JSON-RPC parameters).
#http.route('/division', type="json")
def division(self, i, j):
return i / j # returns a number
Both of them are about communication between client and server. HttpRequest communicates trough the well known GET and POST methods. That means the following:
The client send a request encoded in the url (GET method) or in the http body (POST method)
The server returns an object corresponding to the request. Could be an html page, PNG image, CSS file, JavaScript, XML encoded data or whatever.
JsonRequest is an implementation of another protocol for client/server communication - JSON-RPC 2.0. You may want lo took here form more information. It's a remote procedure call (RPC) protocol which means that it allows the client to initiate the execution of some method on the server passing some arguments to this method. In response the client gets some data as a result of the method invocation.
EDIT - some more words about the decorators #openerpweb.jsonrequest and #openerpweb.httprequest
Some methods are decorated with the #openerpweb.jsonrequest decorator, other methods - with the #openerpweb.httprequest. This means nothing else but that the first group of methods will be available for execution trough the JSON RPC protocol and the second group will be accessible trough the pure HTTP protocol.
Now, what is the difference? I do we need both jsonrequest and httprequest? Let simplify it like this: JSON is more suitable for executing methods on the server and obtain results. HTTP is simpler and easier to use when all we what is to access some resource on the server.
Let's 'decorate' this with some examples for clarity. Take a look at the following method of the web.controllers.main.Export class:
#openerpweb.jsonrequest
def formats(self, req):
""" Returns all valid export formats
:returns: for each export format, a pair of identifier and printable name
:rtype: [(str, str)]
"""
...
This method accepts some arguments and returns a list (Python list object) containing all known export formats. It will be called in a programmatic way in some python code on the client side.
On the other side are the 'http' methods - like the method css() of the web.controllers.main.Web class:
#openerpweb.httprequest
def css(self, req, mods=None):
....
All this method does is to return a CSS file to the client. It's a simple action like accessing an image, a HTML web page or whatever other resource on the server. The resource we are returning here is nothing complicated as a Python list as in the previous example. We don't need a special format to encode it additionally. So we don't need additional data encoding format as JSON and remote procedure call protocol as JSON RPC.
type="json":
it will call JSONRPC as an argument to http.route() so here , there will be only JSON data be able to pass via JSONRPC, It will only accept json data object as argument.
type="http":
As compred to JSON, http will pass http request arguments to http.route() not json data.
Examples
#http.route('demo_html', type="http") // Work Pefrect when I call this URL
def some_html(self):
return "<h1>This is a test</h1>"
#http.route('demo_json', type="json") // Not working when I call this URL
def some_json(self):
return {"sample_dictionary": "This is a sample JSON dictionary"}