Good Day I've alter the website_hr_recruitment module to add some function to download some file. But an Error has occcured when I try to download the file without user access. The error is
{"message": "Odoo Server Error", "code": 200, "data": {"debug": "Traceback (most recent call last):\n File \"/opt/odoo/odoo-server/addons/web/controllers/main.py\", line 70, in wrap\n return f(*args, **kwargs)\n File \"/opt/odoo/odoo-server/addons/web/controllers/main.py\", line 1092, in saveas\n res = Model.read(cr, uid, [int(id)], fields, context)[0]\n File \"/opt/odoo/odoo-server/openerp/api.py\", line 268, in wrapper\n return old_api(self, *args, **kwargs)\n File \"/opt/odoo/odoo-server/openerp/addons/base/ir/ir_attachment.py\", line 318, in read\n self.check(cr, uid, ids, 'read', context=context)\n File \"/opt/odoo/odoo-server/openerp/api.py\", line 268, in wrapper\n return old_api(self, *args, **kwargs)\n File \"/opt/odoo/odoo-server/openerp/addons/base/ir/ir_attachment.py\", line 260, in check\n raise except_orm(_('Access Denied'), _(\"Sorry, you are not allowed to access this document.\"))\nexcept_orm: (u'Access Denied', u'Sorry, you are not allowed to access this document.')\n", "exception_type": "except_osv", "message": "Access Denied\nSorry, you are not allowed to access this document.", "name": "openerp.exceptions.except_orm", "arguments": ["Access Denied", "Sorry, you are not allowed to access this document."]}}
Heres the Model
#http.route('/jobs/apply/<model("hr.job"):job>', type='http', auth="public", website=True)
def jobs_apply(self, job):
error = {}
default = {}
#Added by SDS 19022016
attachment = http.request.env['ir.attachment'].sudo().search([('name', '=', 'Application-Form-rev2.docx')])
#str_url = 'http://localhost:8069'+'/web/binary/saveas?model=ir.attachment&field=datas&filename_field=name&id='+str(attachment.id)
str_url = request.httprequest.host_url +'web/binary/saveas?model=ir.attachment&field=datas&filename_field=name&id='+str(attachment.id)
if 'website_hr_recruitment_bahia_error' in request.session:
error = request.session.pop('website_hr_recruitment_bahia_error')
default = request.session.pop('website_hr_recruitment_bahia_default')
return request.render("website_hr_recruitment_bahia.apply", {
'job': job,
'error': error,
'default': default,
'url_link': str_url,
})
and heres the Template
<div t-attf-class="form-group #{error.get('first_name') and 'has-error' or ''}">
Click ”<a t-att-href="url_link" >Apply Now</a> ” to download, fill-out and upload below
<label class="col-md-3 col-sm-4 control-label" for="first_name">First Name</label>
<div class="col-md-7 col-sm-8">
<input type="text" t-att-value="default.get('first_name')" class="form-control" name="first_name" required="True"/>
</div>
</div>
I tried to add the sudo access but it has no use can someone help me
Thanks
Please create a security file named - ir.model.access.csv
Add it in __openerp__.py like this -
'data': [
'security/ir.model.access.csv',
'views/your_view.xml',
]
Above security is the folder name and in it the file ir.model.access.csv exist.
And add following lines to your csv file-
id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
access_YOUR_CLASS_NAME,access_YOUR_CLASS_NAME,model_YOUR_CLASS_NAME,,1,1,1,1
This should solve the access problem.
Unfortunately, v8 has a more restrictive policy on ir.attachment object and it only let Employee (base.group_user) group read all document i.e. user have to be logged in to access the document(s). So adding record rule or Access Control List rule will not help you.
The best solution here it's to over-ride the def check method on ir.attachment and make more relax to checking the security of accessing documents publically, or maybe you can just over-ride and do not put any logic and make object security driven by ir.attachment. or you can also let some model document bypass from security check.
Hope this will help you.
Bests
Related
I have an API served with FastAPI working on:
http://127.0.0.1:8000/predictions
And I want to test it using Locust. My code:
from locust import HttpUser, TaskSet, task
import json
class UserBehavior(TaskSet):
#task(1)
def create_post(self):
headers = {'content-type': 'application/json','Accept-Encoding':'gzip'}
self.client.post("/predictions",data= json.dumps({
"text": "I am tired",
}),
headers=headers,
name = "Create a new post")
class WebsiteUser(HttpUser):
task=[UserBehavior]
I get this error msg while locust is running:
2022-07-23 16:33:32,764] pop-os/ERROR/locust.user.task: No tasks defined on WebsiteUser. use the #task decorator or set the tasks property of the User (or mark it as abstract = True if you only intend to subclass it)
Traceback (most recent call last):
File "/home/statspy/anaconda3/lib/python3.9/site-packages/locust/user/task.py", line 340, in run
self.schedule_task(self.get_next_task())
File "/home/statspy/anaconda3/lib/python3.9/site-packages/locust/user/task.py", line 472, in get_next_task
raise Exception(
Exception: No tasks defined on WebsiteUser. use the #task decorator or set the tasks property of the User (or mark it as abstract = True if you only intend to subclass it)
How can I fix it?
Thanks
Its tasks=[UserBehavior] , not task=[UserBehavior]
Please guide.
Creating a new mobile app, not able to signup! Returns some error while tryting to call /web/signup and also while directly calling res.users create as sudo.
Please see the error message
The above exception was the direct cause of the following exception:
Traceback (most recent call last): File
"/odoo/odoo-server/odoo/http.py", line 640, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception) File
"/odoo/odoo-server/odoo/http.py", line 316, in _handle_exception raise
exception.with_traceback(None) from
new_causepsycopg2.errors.UndefinedFunction: operator does not exist:
integer = booleanLINE 6: AND (p.company_id=false OR p.company_id ...
Seems this error raised from _get_multi function in ir_property.py
Thanks in advance
I use a custom controller for receiving request from mobile app and tries to call Odoo Core signup (do_signup located in auth_signup/controller/main) function. It reaches up to there and exceution moves to ir_property and returns error as mentioned.
Please see the sample code which try to use
user = {
'name' : user_info['name'],
'phone': user_info['phone'],
'email': 'test#example.com',#user_info['email'] ,
'login': user_info['phone'],
'password': password,
'confirm_password': password,
}
user_info = AuthSignupHome().do_signup(user)
But /web/signup it's a website service type='http'. You need a controller type='json' for call it from your custom mobile app.
I hope this answer can help you.
I created a public route in Odoo10 with type json and i tried to call it from a API clinet( ARC), i am getting 404 Not found error. I don't know why.
Here is my code
controller.py
# -*- coding: utf-8 -*-
from odoo import http,tools
from odoo.http import request, Response
import requests
class TestURL(http.Controller):
#http.route('/create_lead', type="json", method=['POST'], auth='public', csrf=False)
def createLead(self,**kw):
print('Inside create lead')
// rest of the code here
Here is the response i am getting in api client:
{"jsonrpc": "2.0", "id": null, "error": {"message": "404: Not Found", "code": 404, "data": {"debug": "Traceback (most recent call last):\n File \"/home/user/Projects/odoo-10/odoo/http.py\", line 642, in _handle_exception\n return super(JsonRequest, self)._handle_exception(exception)\n File \"/home/user/Projects/odoo-10/odoo/http.py\", line 1471, in _dispatch_nodb\n func, arguments = self.nodb_routing_map.bind_to_environ(request.httprequest.environ).match()\n File \"/usr/local/lib/python2.7/dist-packages/werkzeug/routing.py\", line 1581, in match\n raise NotFound()\nNotFound: 404 Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.\n", "exception_type": "internal_error", "message": "404 Not Found: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.", "name": "werkzeug.exceptions.NotFound", "arguments": []}, "http_status": 404}}
Try
#http.route(['/create_lead']...
and check the identation
I'm a new in flask and boto3 and want create a simple upload form to s3 amazon and i need to save file on s3 with the existing filename and return link to this file.
Two issues:
1) In the example below file always uploads with a name 'test'. If upload file name will be 'my file.pdf' i need to upload file to s3 with the same name ('file.pdf').
I believe it can be done with request but i do not know how exactly. How it can be done?
2) How to return link to the file that i just have uploaded? (I have no idea)
below is my code
#app.route('/')
def index():
return '''
<form method="post" enctype="multipart/form-data" action="upload">
<input type="file" name="file" multiple>
<input type="submit">
</form>
'''
#app.route('/upload', methods=['POST', 'GET'])
def upload():
s3 = boto3.resource('s3')
s3.Bucket('dimkzn').put_object(='test', Body=request.files['file'])
return 'file save! to S3'
if name=='main':
app.run(debug=True) code here
In your upload function you are missing the Key parameter names where you have ="test" which is why every file is being saved as test. You can pass through the filename from the file object within request.files
#app.route('/upload', methods=['POST', 'GET'])
def upload():
s3 = boto3.resource('s3')
s3.Bucket('dimkzn').put_object(Key=request.files['file'].filename, Body=request.files['file'])
return 'file save! to S3'
The URL path will then be https://s3-<region>.amazonaws.com/dimkzn/<filename>
If you wish to upload the file into a subfolder, folders don't actually exist within S3 but you can create folder structures by changing the key of the file. E.G
#app.route('/upload', methods=['POST', 'GET'])
def upload():
s3 = boto3.resource('s3')
s3.Bucket('dimkzn').put_object(Key=f"media/example/{request.files['file'].filename}", Body=request.files['file'])
return 'file save! to S3'
Will upload the file to:
https://s3-<region>.amazonaws.com/dimkzn/media/example/<filename>
I think your problem is in the line:
s3.Bucket('dimkzn').put_object(='test', Body=request.files['file'])
You're missing an argument name before the ='test'. I can't see from your code what request.files['file'] returns: is that the filename or the file content?
Correct syntax is
object = bucket.put_object(
Body=b'bytes'|file,
Key='filename')
...where Body is the content of the file, Key is the filename.
Once successful, you can construct the link yourself as follows:
https://s3-<region>.amazonaws.com/<bucketname>/<filename>
Good luck!
Your Missing "Key", should be like this:
s3.Bucket('dimkzn').put_object(Key='test', Body=request.files['file']
Jinja Template Issue when using napalm function within nornir framework.
updated: My hosts are Cisco IOS devices.
I am running this nornir Jinja template script in a python3.6 virtualenv. I have other simple nornir and napalm code running fine, which makes we suspect the issue is related to jinja2 template function i am trying to use.
The error i am receiving is below. Can anyone assist me with spotting the problem?
working nornir script w/ napalm function - Example showing working environment
from nornir.core import InitNornir
from nornir.plugins.tasks import text
from nornir.plugins.tasks.networking import napalm_get, napalm_configure
from nornir.plugins.functions.text import print_title, print_result
from nornir.core.exceptions import NornirExecutionError
import logging
nr = InitNornir(config_file="config.yaml", dry_run=True)
ctil_net = nr.filter(site="ctil", type="network_device")
core = nr.filter(role="core", type="network_device")
results_napalm_get = nr.run(
task=napalm_get, getters=["facts", "interfaces"]
)
print_result(results_napalm_get)
Nornir script causing error:
from nornir.core import InitNornir
from nornir.plugins.tasks import text
from nornir.plugins.tasks.networking import napalm_get, napalm_configure
from nornir.plugins.functions.text import print_title, print_result
from nornir.core.exceptions import NornirExecutionError
import logging
nr = InitNornir(config_file="config.yaml", dry_run=True)
ctil_net = nr.filter(site="ctil", type="network_device")
core = nr.filter(role="core", type="network_device")
def basic_configuration(task):
# Transform inventory data to configuration via a template file
r = task.run(task=text.template_file,
name="Base Template Configuration",
template="base.j2", ## modified
path=f"templates",
severity_level=logging.DEBUG)
# Save the compiled configuration into a host variable
task.host["config"] = r.result
print (r.result)
# Deploy that configuration to the device using NAPALM
task.run(task=networking.napalm_configure,
name="Loading Configuration on the device",
replace=False,
configuration=task.host["config"],
severity_level=logging.INFO)
try:
print_title("Playbook to configure the network")
result = core.run(task=basic_configuration)
print_result(result)
except NornirExecutionError:
print("ERROR!!!")
config.yaml
num_workers: 100
inventory: nornir.plugins.inventory.simple.SimpleInventory
SimpleInventory:
host_file: "inventory/hosts.yaml"
group_file: "inventory/groups.yaml"
base.j2 (template file)
hostname {{ system.hostname }}
ip domain-name {{ site }}.{{ domain }}
base.j2 (template file) - Alt version (same exact error msg / result
hostname {{ host.name }}
ip domain-name {{ site }}.{{ domain }}
Hosts.yaml
switch101:
nornir_host: 192.168.2.101
site: ctil
role: core
groups:
- lab
nornir_nos: ios
type: network_device
switch007:
nornir_host: 192.168.2.7
site: ctil
role: access
groups:
- production
nornir_nos: ios
type: network_device
error output when I run:
$ python adv-nornir-example.py
**** Playbook to configure the network *****************************************
basic_configuration*************************************************************
* switch101 ** changed : False *************************************************
vvvv basic_configuration ** changed : False vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv ERROR
Subtask: Base Template Configuration (failed)
---- Base Template Configuration ** changed : False ---------------------------- ERROR
Traceback (most recent call last):
File "/home/melshman/projects/virtualenv/nornir/lib/python3.6/site-packages/nornir/core/task.py", line 62, in start
r = self.task(self, **self.params)
File "/home/melshman/projects/virtualenv/nornir/lib/python3.6/site-packages/nornir/plugins/tasks/text/template_file.py", line 26, in template_file
**merged
File "/home/melshman/projects/virtualenv/nornir/lib/python3.6/site-packages/nornir/core/helpers/jinja_helper.py", line 11, in render_from_file
return template.render(**kwargs)
File "/home/melshman/projects/virtualenv/nornir/lib/python3.6/site-packages/jinja2/asyncsupport.py", line 76, in render
return original_render(self, *args, **kwargs)
File "/home/melshman/projects/virtualenv/nornir/lib/python3.6/site-packages/jinja2/environment.py", line 1008, in render
return self.environment.handle_exception(exc_info, True)
File "/home/melshman/projects/virtualenv/nornir/lib/python3.6/site-packages/jinja2/environment.py", line 780, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/melshman/projects/virtualenv/nornir/lib/python3.6/site-packages/jinja2/_compat.py", line 37, in reraise
raise value.with_traceback(tb)
File "templates/base.j2", line 2, in top-level template code
hostname {{ system.hostname }}
File "/home/melshman/projects/virtualenv/nornir/lib/python3.6/site-packages/jinja2/environment.py", line 430, in getattr
return getattr(obj, attribute)
jinja2.exceptions.UndefinedError: 'system' is undefined
^^^^ END basic_configuration ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
You are not passing system to the template. I think what you are trying to do in your template is:
hostname {{ host.name }}
ip domain-name {{ site }}.{{ domain }}
Basically the template, unless you add extra kwargs, is going to have access to the host itself via the host variable and to all of the host attributes specified in the inventory.