Odoo redirect with JSON - odoo

I need to redirect user by pressing a button.
The button code is like that:
from odoo.http import request
...
#api.one
def go_away(self):
return request.redirect('http://example.com/api.jsp?user=1&id=12')
Odoo raises an error:
AttributeError: 'JsonRequest' object has no attribute 'redirect'
When i try this:
werkzeug.utils.redirect(url)
Odoo says:
AttributeError: 'function' object has no attribute 'routing_type'
I can understand what is wrong and how can i redirect user with JSON data in a link.

I found out that i can redirect like this:
#api.multi
def go_away(self)
return {
'type': 'ir.actions.act_url',
'url': url,
'target': 'self',
}

Related

404 error while activating user in djoser (django)

I created class based view to access uid and token . Here I create one web page which have one button of activate user.
I wish to activate user that created. I am receiving the activation link via email. When I click on the link an activation page is opened. this page has a button to activate user. On click the button a post request is executed to activate user but I am getting 404 error.
Activate_User_App/views.py
import json
from common_strings import ACTIVATION_BASE_ROUTE
from django.views import View
from django.shortcuts import render
from django.http import HttpResponse
import requests
class ActivationView(View):
def get (self, request, uid, token):
print('get called in activate')
return render(request, 'activate.html')
def post (self, request, uid, token):
print('UID : ', uid)
print('Token : ', token)
payload = json.dumps({'uid': uid, 'token': token})
print("payload : " , payload)
protocol = 'https://' if request.is_secure() else 'http://'
web_url = protocol + request.get_host() + '/'
post_url = web_url + ACTIVATION_BASE_ROUTE
print('post_url : ' + post_url)
response = requests.post(post_url, data = payload)
print("response : ", response)
return HttpResponse(response.text)
Activate_User_App/urls.py:
urlpatterns = [re_path(r'^(?P<uid>[\w-]+)/(?P<token>[\w-]+)/$',ActivationView.as_view()),]
settings.py
DJOSER = {
'PASSWORD_RESET_CONFIRM_URL': AUTHENTICATION_BASE_ROUTE + 'password/reset/confirm/{uid}/{token}',
'USERNAME_RESET_CONFIRM_URL': AUTHENTICATION_BASE_ROUTE + 'username/reset/confirm/{uid}/{token}',
'ACTIVATION_URL': ACTIVATION_BASE_ROUTE + '{uid}/{token}/',
'SEND_ACTIVATION_EMAIL': True,
'SEND_CONFIRMATION_EMAIL': True,
'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True,
'USERNAME_CHANGED_EMAIL_CONFIRMATION': True,
'USER_CREATE_PASSWORD_RETYPE': True, #Designed to propote good programming practice
'SET_PASSWORD_RETYPE': True, #Designed to propote good programming practice
'PASSWORD_RESET_CONFIRM_RETYPE': True, #Designed to propote good programming practice
'LOGOUT_ON_PASSWORD_CHANGE' : True, #Note : Logout only works with token based authentication. djoser 2.10
'PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND': False, #Please note that setting this to True will expose information whether an email is registered in the system
'USERNAME_RESET_SHOW_EMAIL_NOT_FOUND': False, #Please note that setting this to True will expose information whether an email is registered in the system
'HIDE_USERS': True,
'token': 'djoser.serializers.TokenSerializer',
'token_create': 'djoser.serializers.TokenCreateSerializer',
'LOGIN_FIELD': 'email', #Default: User.USERNAME_FIELD where User is the model set with Django’s setting AUTH_USER_MODEL.
'SERIALIZERS': {
'user': 'user_profile.serializer.UserSerializer',
},
project/urls.py
urlpatterns = [
path(ACTIVATION_BASE_ROUTE, include('Activate_User_App.urls')),
re_path(r'^api/authentication/', include('djoser.urls')),
re_path(r'^api/authentication/', include('djoser.urls.authtoken')),
common_strings
AUTHENTICATION_BASE_ROUTE = 'authentication/user/'
ACTIVATION_BASE_ROUTE = AUTHENTICATION_BASE_ROUTE + 'activate/'
activate.html
<form action="" method="post">
{% csrf_token %}
<td ><button type="submit">Click Here For Activate Account</button></td>
</form>

Scrapy won't let me login to asp.net page (ASPX)

Hi I'm having trouble getting my scrapy spider script to login to a aspx (asp.net) website
The script is supposed to crawl a website for product information (it's a suppliers website so we are allowed to do this) but for whatever reason the script is not able to login to the webpage using the script below, there is a username and password field along with a image button but when the script runs it simply doesn't work and we are redirected to the main page... I believe it has something to do with the page being asp.net and apparently i need to pass more information but i've honestly tried everything and im at a loss of what to do next!
What am I doing wrong?
import scrapy
class LeedaB2BSpider(scrapy.Spider):
name = 'leedab2b'
start_urls = [
'https://www.leedab2b.co.uk/customerlogin.aspx'
]
def parse(self, response):
return scrapy.FormRequest.from_response(response=response,
formdata={'ctl00$ContentPlaceHolder1$tbUsername': 'emailaddress#gmail.com', 'ctl00$ContentPlaceHolder1$tbPassword': 'yourpassword'},
clickdata={'id': 'ctl00_ContentPlaceHolder1_lbcustomerloginbutton'},
callback=self.after_login)
def after_login(self, response):
self.logger.info("you are at %s" % response.url)
FormRequest.from_response doesn't seem to send __EVENTTARGET, __EVENTARGUMENT in formdata, try to add them manually:
formdata={
'__EVENTTARGET': 'ctl00$ContentPlaceHolder1$lbcustomerloginbutton',
'__EVENTARGUMENT': '',
'ctl00$ContentPlaceHolder1$tbUsername': 'emailaddress#gmail.com',
'ctl00$ContentPlaceHolder1$tbPassword': 'yourpassword'
}

How to redirect to a URL by some authentications in ODOO

Hope you all are doing well.
How can we redirect to a thirdparty URL by some authentications(Parameters) through controller. Means we have some crediantials to access the URL..we need to pass these as parameters..
I am successful in redirecting to URL using werkzeug.utils.redirect("URL"), but this does not allow me to use authentications...
Then try this
client_id = "My_Client_Id"
return {
'name': 'Go to website',
'res_model': 'ir.actions.act_url',
'type': 'ir.actions.act_url',
'target': 'self',
'url': 'https://slack.com/oauth/v2/authorize?user_scope=channels:history,channels:read,'
'channels:write,im:write,chat:write&client_id=' + client_id
}
This code will help you or may solve your issue because it is
redirecting you on given URL with my own data(client Id)

How to use "POST url" JSON file in RoR website?

I am using Ruby on Rails and Kibana to show visualisation in my website(Ruby2.6.0, Rails5.2.3, Kibana6.6.1). By using Xpack->Share->Generate PDF/PNG, I find 'copy POST url'. I can get the following JSON file from the POST url by using 'net/http', but how can I use POST url/JSON file in my RoR website to download PNG file in 'assets' folder?
JSON file I got from POST url:
{'path': '/api/reporting/jobs/download/jvds4zs10qv79d0062b9cel6',
'job': {'id': 'jvds4zs10qv79d0062b9cel6', 'index':
'.reporting-2019.05.05', 'type': 'esqueue', 'jobtype': 'PNG',
'created_by': False, 'payload': {'type': 'visualization', 'title':
'[eCommerce] Sales by Gender', 'relativeUrl':
"/app/kibana#/visualize/edit/ed8436b0-b88b-11e8-a6d9-e546fe2bba5f?_g=(refreshInterval:(pause:!t,value:0),time:(from:now-60d,mode:quick,to:now))&_a=(filters:!(),linked:!f,query:(language:lucene,query:''),uiState:(),vis:(aggs:!((enabled:!t,id:'1',params:(),schema:metric,type:count),(enabled:!t,id:'2',params:(field:customer_gender,json:'',missingBucket:!f,missingBucketLabel:Missing,order:desc,orderBy:'1',otherBucket:!f,otherBucketLabel:Other,size:5),schema:segment,type:terms)),params:(addLegend:!t,addTooltip:!t,isDonut:!t,labels:(last_level:!t,show:!t,truncate:100,values:!t),legendPosition:right,type:pie),title:'%5BeCommerce%5D+Sales+by+Gender',type:pie))",
'headers':
'uxY4w6gCRwwLZyFkDX0ujVlANYq7ae5UuNJAN0GpbTOX7vw5aPuCuyr37nNcpz3vtA8kNVaL6Gacs24mPjZfwl4mB9xRKGA62CkCLo8Xz1amuIEthI+BtKPGo5QAk2k2+7zLvLgX3KouVvYdd61U5rLAvfjv4TydcpH9qJ4qrL5OELkzAJGrNdujtDLWaoy2Qj9YXbLnh7gSdI+lrNml6usZIh4pMzz8qdRo597iO/4AeSJRa2JfAruyGB3zYInZRtMuCbA4f3ANvT2WeAn6lpiwThB993uEjwu4LBVUZuo2XL0TcB29YNNa9oMCUEhWjdJ1ase5VQdz8V2IOgecQ1W52V5JuVTvl9SkVvFWSBhXJg==',
'browserTimezone': 'Europe/Zurich', 'layout': {'dimensions':
{'height': 589.234375, 'width': 866}}, 'basePath': '', 'forceNow':
'2019-05-07T12:38:12.768Z'}, 'timeout': 120000, 'max_attempts': 3,
'priority': 10, 'browser_type': 'chromium'}}
I am trying to use 'net/http', What I added in controller:
class MaisonController < ApplicationController
require 'net/http'
def require_post
uri = URI.parse("http://localhost:5601/api/reporting/generate/png?jobParams=(browserTimezone:Europe%2FZurich,layout:(dimensions:(height:589.234375,width:866)),objectType:visualization,relativeUrl:%27%2Fapp%2Fkibana%23%2Fvisualize%2Fedit%2Fed8436b0-b88b-11e8-a6d9-e546fe2bba5f%3F_g%3D(refreshInterval:(pause:!!t,value:0),time:(from:now-60d,mode:quick,to:now))%26_a%3D(filters:!!(),linked:!!f,query:(language:lucene,query:!%27!%27),uiState:(),vis:(aggs:!!((enabled:!!t,id:!%271!%27,params:(),schema:metric,type:count),(enabled:!!t,id:!%272!%27,params:(field:customer_gender,json:!%27!%27,missingBucket:!!f,missingBucketLabel:Missing,order:desc,orderBy:!%271!%27,otherBucket:!!f,otherBucketLabel:Other,size:5),schema:segment,type:terms)),params:(addLegend:!!t,addTooltip:!!t,isDonut:!!t,labels:(last_level:!!t,show:!!t,truncate:100,values:!!t),legendPosition:right,type:pie),title:!%27%255BeCommerce%255D%2BSales%2Bby%2BGender!%27,type:pie))%27,title:%27%5BeCommerce%5D%20Sales%20by%20Gender%27)")
http = Net::HTTP.new(uri.host,uri.port)
request = Net::HTTP::Post.new(uri.request_uri)
response = http.request(request)
render :json => response.body
end
end
Edit:
I try to use 'attachment_fu' gem to download png file with the above JSON file. Modify the code in Controller to the following code:
class MaisonController < ApplicationController
require 'net/http'
require 'open-uri'
def require_post
uri = URI.parse("http://localhost:5601/api/reporting/generate/png?jobParams=(browserTimezone:Europe%2FZurich,layout:(dimensions:(height:589.234375,width:866)),objectType:visualization,relativeUrl:%27%2Fapp%2Fkibana%23%2Fvisualize%2Fedit%2Fed8436b0-b88b-11e8-a6d9-e546fe2bba5f%3F_g%3D(refreshInterval:(pause:!!t,value:0),time:(from:now-60d,mode:quick,to:now))%26_a%3D(filters:!!(),linked:!!f,query:(language:lucene,query:!%27!%27),uiState:(),vis:(aggs:!!((enabled:!!t,id:!%271!%27,params:(),schema:metric,type:count),(enabled:!!t,id:!%272!%27,params:(field:customer_gender,json:!%27!%27,missingBucket:!!f,missingBucketLabel:Missing,order:desc,orderBy:!%271!%27,otherBucket:!!f,otherBucketLabel:Other,size:5),schema:segment,type:terms)),params:(addLegend:!!t,addTooltip:!!t,isDonut:!!t,labels:(last_level:!!t,show:!!t,truncate:100,values:!!t),legendPosition:right,type:pie),title:!%27%255BeCommerce%255D%2BSales%2Bby%2BGender!%27,type:pie))%27,title:%27%5BeCommerce%5D%20Sales%20by%20Gender%27)")
http = Net::HTTP.new(uri.host,uri.port)
request = Net::HTTP::Post.new(uri.request_uri)
response = http.request(request)
render :json => response.body
http.start() { |http|
tempfile = Tempfile.new('test.png')
File.open(tempfile.path, 'w') do |f|
f.write response.body
end
attachment = Attachment.new(:upload_data => LocalFile.new(tempfile.path))
attachment.save
}
end
The error I get is 'uninitialized constant MaisonController::Attachment'.
Expected result: download png file in assets by using the above JSON file.
I will answer my own question about what I tried in my project and close this question.
I got 'copy POST url' in 'Kibana->Visualisation/Dashboard->PDF/PNG'. It is a post url. I sent post request with this url to kibana server. The action will trigger kibana server to 'pending', 'processing' and generate the report. And I will get a JSON file back from the server. There is an important job ID in JSON file, like this 'jvi53ajd21w09d006233kcvo'. I can find all history reports in 'Management->Reporting'. Finally, I use the generated url 'http://localhost:5601/api/reporting/jobs/download/jvi53ajd21w09d006233kcvo' with 'wget' command to download the report in my local folder.
You can find similar answer here: https://discuss.elastic.co/t/how-to-use-post-url-to-share-visualisation-in-my-website/179671/4
Hope my answer can help those who want to use POST URL in Kibana.

How to redirect from one controller to another with params in odoo?

I have created a registration page for new user and company.I dont want to use default signup page which is already there because I have many custom fields. After creating new user and company I want to display user details in a new page. I am getting error as TypeError: 'dict' object is not callable. How to redirect from '/web/save' api to '/web/details' api with my parameter 'qcontext'.
#http.route('/web/save', type='http', method="post", auth="public",csrf=False)
def save_registration_details(self, **kw):
qcontext = request.params.copy()
# Code to create new user and company
return {
'type': 'ir.actions.act_url',
'url': '/web/details/%s' % qcontext,
'target': 'self',
}
#http.route('/web/details', type='http', auth="public")
def show_registration_details(self, qcontext, redirect=None, **kw):
return http.request.render('odoo_web_login.success',qcontext)
You can try:
return werkzeug.utils.redirect('/web/details%s' % qcontext)
For redirect from One controller to another return url like this:
return {
'type': 'ir.actions.act_url',
'url': '/web/details?qcontext=%s&redirect=True' % (qcontext),
'target': 'self',
}