Automated Actions in odoo 12. Set values with python code - python

I tried to take text from one field and set it modificated to another throught Execute Python Code.
recs = record.smt
for rec in recs:
details = pythonwhois.get_whois(rec)
if 'No match for' in str(details):
record.smt2='ok'
else:
record.smt2='denied'
Error: forbidden opcode
Please, help!

For the line:
details = pythonwhois.get_whois(rec)
You are using a external library pythonwhois which is not imported, how do you suppose to use that in your execution. As import statement is also not allowed, you can't just import any library.
instead of using dot operator, try to use write function.
if 'No match for' in str(details):
smt2='ok'
else:
smt2='denied'
record.write({'smt2': smt})
Also keep in mind that record is the record on which the action is triggered; may be void

Related

Unable to extract all feature data for a project using pyral's rest api python

I'm trying to read all feature data for a project in Rally using pyral module. The total result set count is 1358 and the script throws error as mentioned below after reading some 700 records.
rally1 = Rally(entity='PortfolioItem_Feature',server='rally1.rallydev.com',fetch=True, user='xxx', password='', workspace='xxx/yyy', project='ABC')
features = rally1.get('Feature',fetch="True",pagesize=2000,start=0,limit=5000)
for feature in features:
#a=pd.DataFrame(feature)
print(feature.details())
OUTPUT:
PortfolioItem/Feature result set, totalResultSetSize: 1358, startIndex: 1 pageSize: 2000 current Index: 0
I'm getting the following errors:
File "C:\Users\nis\AppData\Roaming\Python\Python38\site-packages\pyral\entity.py", line 397, in details
(attr_name, cln, value.oid, value.UserName, value.DisplayName)
File "C:\Users\nis\AppData\Roaming\Python\Python38\site-packages\pyral\entity.py", line 139, in __getattr__
raise UnreferenceableOIDError("%s OID %s" % (rallyEntityTypeName, self.oid))
pyral.entity.UnreferenceableOIDError: User OID 44012386960
So, I have following questions:
How can I fix this error, meaning skip reading that particular field for the feature attributes or replace that with empty result set.
How can I convert the (a) <class 'pyral.rallyresp.RallyRESTResponse'> (b) PortfolioItem/Feature result set to dataframe without getting the error as mentioned above.
I am using the below code and this script too reads approx. 700 records and throws the same error as mentioned above. I tried using error handing still it stops reading at the point where it encounters error. Any help will be greatly appreciated.
r=pd.DataFrame()
for feature in features:
a= {
'OID': feature.oid,
'FeatureID':feature.FormattedID,
'Creation_Date': feature.CreationDate,
'Project_Name': feature.Project.Name,
'AcceptedLeafStoryPlanEstimateTotal':feature.AcceptedLeafStoryPlanEstimateTotal,
'AcceptedLeafStoryPlanEstimateTotal':feature.AcceptedLeafStoryPlanEstimateTotal,
'Feature_payload':feature._ref,
'Created by':feature.CreatedBy.DisplayName
}
#print(a.keys())
#print(a.values())
r=r.append(a,ignore_index=True,sort=False)
print(r)
Looks to me like the object with id 44012386960 is broken so you'll have to skip it.
for feature in features:
if feature.oid == 44012386960:
continue
print(feature.details())
I'm assuming that your error is a bad featureoid because it also happens in your second loop which only uses feature.oid but it's also possible that feature.CreatedBy is the problem because your error message suggests that it's a bad user oid. In that care my suggestion would be to print feature.CreatedBy.oid in your loop to find the bad one and change my if to if feature.CreatedBy.oid == 44012386960: continue
I resolved the issue using ternary operators in python as shown below:
feature_name = '' if feature.Feature is None else feature.Feature.Name
The issue was whenever Rally rest api was unable to reference the oid for a particular feature that caused an error.

Python-How to execute code and store into variable?

So I have been struggling with this issue for what seems like forever now (I'm pretty new to Python). I am using Python 3.7 (need it to be 3.7 due to variations in the versions of packages I am using for the project) to develop an AI chatbot system that can converse with you based on your text input. The program reads the contents of a series of .yml files when it starts. In one of the .yml files I am developing a syntax for when the first 5 characters match a ^###^ pattern, it will instead execute the code and return the result of that execution rather than just output text back to the user. For example:
Normal Conversation:
- - What is AI?
- Artificial Intelligence is the branch of engineering and science devoted to constructing machines that think.
Service/Code-based conversation:
- - Say hello to me
- ^###^print("HELLO")
The idea is that when you ask it to say hello to you, the ^##^print("HELLO") string will be retrieved from the .yml file, the first 5 characters of the response will be removed, the response will be sent to a separate function in the python code where it will run the code and store the result into a variable which will be returned from the function into a variable that will give the nice, clean result of HELLO to the user. I realize that this may be a bit hard to follow, but I will straighten up my code and condense everything once I have this whole error resolved. As a side note: Oracle is just what I am calling the project. I'm not trying to weave Java into this whole mess.
THE PROBLEM is that it does not store the result of the code being run/executed/evaluated into the variable like it should.
My code:
def executecode(input):
print("The code to be executed is: ",input)
#note: the input may occasionally have single quotes and/or double quotes in the input string
result = eval("{}".format(input))
print ("The result of the code eval: ", result)
test = eval("2+2")
test
print(test)
return result
#app.route("/get")
def get_bot_response():
userText = request.args.get('msg')
print("Oracle INTERPRETED input: ", userText)
ChatbotResponse = str(english_bot.get_response(userText))
print("CHATBOT RESPONSE VARIABLE: ", ChatbotResponse)
#The interpreted string was a request due to the ^###^ pattern in front of the response in the custom .yml file
if ChatbotResponse[:5] == '^###^':
print("---SERVICE REQUEST---")
print(executecode(ChatbotResponse[5:]))
interpreter_response = executecode(ChatbotResponse[5:])
print("Oracle RESPONDED with: ", interpreter_response)
else:
print("Oracle RESPONDED with: ", ChatbotResponse)
return ChatbotResponse
When I run this code, this is the output:
Oracle INTERPRETED input: How much RAM do you have?
CHATBOT RESPONSE VARIABLE: ^###^print("HELLO")
---SERVICE REQUEST---
The code to be executed is: print("HELLO")
HELLO
The result of the code eval: None
4
None
The code to be executed is: print("HELLO")
HELLO
The result of the code eval: None
4
Oracle RESPONDED with: None
Output on the website interface
Essentially, need it to say HELLO for the "The result of the code eval:" output. This should get it to where the chatbot responds with HELLO in the web interface, which is the end goal here. It seems as if it IS executing the code due to the HELLO's after the "The code to be executed is:" output text. It's just not storing it into a variable like I need it to.
I have tried eval, exec, ast.literal_eval(), converting the input to string with str(), changing up the single and double quotes, putting \ before pairs of quotes, and a few other things. Whenever I get it to where the program interprets "print("HELLO")" when it executes the code, it complains about the syntax. Also, from several days of looking online I have figured out that exec and eval aren't generally favored due to a bunch of issues, however I genuinely do not care about that at the moment because I am trying to make something that works before I make something that is good and works. I have a feeling the problem is something small and stupid like it always is, but I have no idea what it could be. :(
I used these 2 resources as the foundation for the whole chatbot project:
Text Guide
Youtube Guide
Also, I am sorry for the rather lengthy and descriptive question. It's rare that I have to ask a question of my own on stackoverflow because if I have a question, it usually already has a good answer. It feels like I've tried everything at this point. If you have a better suggestion of how to do this whole system or you think I should try approaching this another way, I'm open to ideas.
Thank you for any/all help. It is very much appreciated! :)
The issue is that python's print() doesn't have a return value, meaning it will always return None. eval simply evaluates some expression, and returns back the return value from that expression. Since print() returns None, an eval of some print statement will also return None.
>>> from_print = print('Hello')
Hello
>>> from_eval = eval("print('Hello')")
Hello
>>> from_print is from_eval is None
True
What you need is a io stream manager! Here is a possible solution that captures any io output and returns that if the expression evaluates to None.
from contextlib import redirect_stout, redirect_stderr
from io import StringIO
# NOTE: I use the arg name `code` since `input` is a python builtin
def executecodehelper(code):
# Capture all potential output from the code
stdout_io = StringIO()
stderr_io = StringIO()
with redirect_stdout(stdout_io), redirect_stderr(stderr_io):
# If `code` is already a string, this should work just fine without the need for formatting.
result = eval(code)
return result, stdout_io.getvalue(), stderr_io.getvalue()
def executecode(code):
result, std_out, std_err = executecodehelper(code)
if result is None:
# This code didn't return anything. Maybe it printed something?
if std_out:
return std_out.rstrip() # Deal with trailing whitespace
elif std_err:
return std_err.rstrip()
else:
# Nothing was printed AND the return value is None!
return None
else:
return result
As a final note, this approach is heavily linked to eval since eval can only evaluate a single statement. If you want to extend your bot to multiple line statements, you will need to use exec, which changes the logic. Here's a great resource detailing the differences between eval and exec: What's the difference between eval, exec, and compile?
It is easy just convert try to create a new list and add the the updated values of that variable to it, for example:
if you've a variable name myVar store the values or even the questions no matter.
1- First declare a new list in your code as below:
myList = []
2- If you've need to answer or display the value through myVar then you can do like below:
myList.append(myVar)
and this if you have like a generator for the values instead if you need the opposite which means the values are already stored then you will just update the second step to be like the following:
myList[0]='The first answer of the first question'
myList[1]='The second answer of the second question'
ans here all the values will be stored in your list and you can also do this in other way, for example using loops is will be much better if you have multiple values or answers.

Check if filter exists

I am using jira-python with Python 2.7 and Jira Server to set up components and filters. I want to add new filters when needed and update existing ones when applicable. From the non-progress of this request; JRASERVER-36045, I am not optimistic about the prospects of retrieving a list of existing (public) filters. I was however hoping that I would be able to use a Try/Except block to create a filter, like so:
try:
jira.create_filter(name=name_of_filter, jql=filter_str)
except JIRAError:
jira.update_filter(name=name_of_filter, jql=filter_str)
However, first of all, I get
NameError: name 'JIRAError' is not defined
What error type should I use?
Second; I think I need to provide a filter-ID instead of name to update it. But can I somehow get hold of the filter ID if I know the filter name?
To you first question: you will need to import JIRAError to use it. Something more like:
from jira import JIRA
from jira import JIRAError
jira = JIRA('https://jira.atlassian.com')
try:
jira.create_filter(name=name_of_filter, jql=filter_str)
except JIRAError:
jira.update_filter(name=name_of_filter, jql=filter_str)

How to use python Transaction without database ?

I have two line in my code which first one is os.unlink and second one is os.symlink. like :
os.unlink(path)
os.symlink(new_path)
The sequence should not be change, The problem is, some times it unlink a file (in other word it remove it's shortcut) but second line could not create symbolic link (do to some addressing issue).
My question is: Is there any all or non transaction tool like the one we have in database, to do both line or non ?
you could try this:
import os
linkname = '/tmp/test.lnk'
orig_target = os.path.realpath(linkname)
os.unlink(linkname)
try:
os.symlink(new_target, linkname)
except:
os.symlink(orig_target, linkname)
maybe check what exceptions can occur and only catch the ones that are relevant.
Strictly speaking it is not possible unless you use Transactional filesystem like TxF (https://en.wikipedia.org/wiki/Transactional_NTFS) because nothing prevents your machine from poweroff between two commands.
I can see 2 ways here:
1) Switch to Database
2) Check all conditions before unlinking. What prevents you from symlinking?

Error on getting data from twitter

import twitter
api=twitter.Api()
page=1
count=0
while(page<=2):
tweets=api.GetSearch("#ghaza",per_page=200)
twitterapi.until:2011-05-09
for k in tweets:
print k.text
page+=1
I run the code, code run correctly when I didn't enter the twitterapi.until:2011-05-09 but I want data about specific date's but It give scientific error on it. I notice the above code syntax on https://dev.twitter.com/docs/using-search.
If you look at the documentation, you'll find until is to be used within the search query.
Here your usage to until: violates Python Syntax as the colon is used in
function & class definition, conditionals and loops. And also twitterapi.until will be undefined.
So, I believe you should change tweets=api.GetSearch("#ghaza",per_page=200) to tweets=api.GetSearch("#ghaza until:2011-05-09",per_page=200). That if the select query in the api is "#ghaza".

Categories

Resources