how to make parse of list(string) not list(char) in parse argument of list? - python-3.x

I use flask_restful in flask
My code like:
from flask_restful import Resource, reqparse
apilink_parser = reqparse.RequestParser()
apilink_parser.add_argument('provider_id', type=int,required=True)
apilink_parser.add_argument('name', type=str, required=True)
apilink_parser.add_argument('func_id', type=int)
apilink_parser.add_argument('method', type=str)
apilink_parser.add_argument('url', type=str)
apilink_parser.add_argument('parameter',type=list)
apilink_parser.add_argument("expectreturn", type=list)
#marshal_with(apilink_fields)
def post(self):
args = apilink_parser.parse_args()
print(args)
# user owns the task
task = APILink.create(**args)
return task, 201
My json post data like:
{
"name":"riskiqwhois",
"provider_id":1,
"func_id":1,
"url":"myurl",
"parameter":["query"], //******//
"expectreturn":[],
"method":"post"
}
but when I print the arrgs the result is:
{
'provider_id': 1,
'name': 'riskiqwhois',
'func_id': 1,
'method': 'post',
'url': 'myurl',
'parameter': ['q', 'u', 'e', 'r', 'y'], //******//
'expectreturn': None
}
I want
You can see I want parameter is list of string which is only one element named "query", but the real parameter tranlate into the database is ['q', 'u', 'e', 'r', 'y'], How to make the parameter is list of string not list of char? how to make sure the data is list(string)?

Well, you forgot to set action="append" and you should change from type=list to type=str.
If not, you will still be getting a result like [['q', 'u', 'e', 'r', 'y']].
...
apilink_parser.add_argument('parameter',type=str, action='append')
apilink_parser.add_argument("expectreturn", type=str, action='append')

You can solve this problem by adding action="append" to your request parser
like below
apilink_parser.add_argument('parameter',type=str,action="append")
apilink_parser.add_argument("expectreturn", type=list,action="append")
this will return you below output
{
'provider_id': 1,
'name': 'riskiqwhois',
'func_id': 1,
'method': 'post',
'url': 'myurl',
'parameter': ['query'],
'expectreturn': None
}

Related

API to pull the list of supported languages in AWS Translate

I am currently working on a project where I need to translate Customer comments into English from the source language on AWS. It is easy to do so using AWS Translate but before I call translate API to translate text into English, I want to check whether the source language is supported by AWS or not?
One solution is to put all the language codes supported by AWS Translate into a list and then check source language against this list. This is easy but it is going to be messy and I want to make it more dynamic.
So, I am thinking to code like this
import boto3
def translateUserComment(source_language):
translate = boto3.client(service_name='translate', region_name='region', use_ssl=True)
languages_supported = tanslate.<SomeMethod>()
if source_language in languages_supported:
result = translate.translate_text(Text="Hello, World",
SourceLanguageCode=source_language, TargetLanguageCode="en")
print('TranslatedText: ' + result.get('TranslatedText'))
print('SourceLanguageCode: ' + result.get('SourceLanguageCode'))
print('TargetLanguageCode: ' + result.get('TargetLanguageCode'))
else:
print("The source language is not supported by AWS Translate")
Problem is that I am not able to find out any API call to get the list of languages/language codes supported by AWS Translate for place.
Before I posted this question,
I have tried to search for similar questions on stackoverflow
I have gone through the AWS Translate Developer guide but still no luck
Any suggestion/ redirection to the right approach is highly appreciated.
Currently there is no API for this service, although this code would work, in this code a class is created Translate_lang with all the language codes and country wise
from here-> https://docs.aws.amazon.com/translate/latest/dg/what-is.html
, you can call this class into your program and use it by creating an instance of the class:
translate_lang_check.py
class Translate_lang:
def __init__(self):
self.t_lang = {'Afrikaans': 'af', 'Albanian': 'sq', 'Amharic': 'am',
'Arabic': 'ar', 'Armenian': 'hy', 'Azerbaijani': 'az',
'Bengali': 'bn', 'Bosnian': 'bs', 'Bulgarian': 'bg',
'Catalan': 'ca', 'Chinese (Simplified)': 'zh',
'Chinese (Traditional)': 'zh-TW', 'Croatian': 'hr',
'Czech': 'cs', 'Danish': 'da ', 'Dari': 'fa-AF',
'Dutch': 'nl ', 'English': 'en', 'Estonian': 'et',
'Farsi (Persian)': 'fa', 'Filipino Tagalog': 'tl',
'Finnish': 'fi', 'French': 'fr', 'French (Canada)': 'fr-CA',
'Georgian': 'ka', 'German': 'de', 'Greek': 'el', 'Gujarati': 'gu',
'Haitian Creole': 'ht', 'Hausa': 'ha', 'Hebrew': 'he ', 'Hindi': 'hi',
'Hungarian': 'hu', 'Icelandic': 'is', 'Indonesian': 'id ', 'Italian': 'it',
'Japanese': 'ja', 'Kannada': 'kn', 'Kazakh': 'kk', 'Korean': 'ko',
'Latvian': 'lv', 'Lithuanian': 'lt', 'Macedonian': 'mk', 'Malay': 'ms',
'Malayalam': 'ml', 'Maltese': 'mt', 'Mongolian': 'mn', 'Norwegian': 'no',
'Persian': 'fa', 'Pashto': 'ps', 'Polish': 'pl', 'Portuguese': 'pt',
'Romanian': 'ro', 'Russian': 'ru', 'Serbian': 'sr', 'Sinhala': 'si',
'Slovak': 'sk', 'Slovenian': 'sl', 'Somali': 'so', 'Spanish': 'es',
'Spanish (Mexico)': 'es-MX', 'Swahili': 'sw', 'Swedish': 'sv',
'Tagalog': 'tl', 'Tamil': 'ta', 'Telugu': 'te', 'Thai': 'th',
'Turkish': 'tr', 'Ukrainian': 'uk', 'Urdu': 'ur', 'Uzbek': 'uz',
'Vietnamese': 'vi', 'Welsh': 'cy'}
def check_lang_in_translate(self, given_country):
if given_country in self.t_lang:
return self.t_lang[given_country]
else:
return None
def check_lang_code_in_translate(self, given_lang):
if given_lang in list(self.t_lang.values()):
return True
else:
return False
You can call and check your lang codes using the methods of this class:
from translate_lang_check import Translate_lang
tl = Translate_lang()
print(tl.check_lang_code_in_translate('en'))

Syntax Error: TypeError: Cannot read property 'kind' of null for Enum using Vue 3 and TypeScript

I'm defining an enum within a Vue 3 component like so:
<script lang="ts">
import { defineComponent } from 'vue'
export enum PieceType
{
None,
Pawn,
Rook,
Knight,
Bishop,
Queen,
King
}
export interface Piece
{
position: Position,
type: PieceType,
}
export interface Position
{
row: number,
col: number
}
export default defineComponent({
props: {
type: String,
row: Number,
col: Number
},
setup(props) {
const getPiece = (piece: string) =>
{
console.log("Piece is:", piece)
switch(piece)
{
case "R": return PieceType.Rook;
case "K": return PieceType.Knight;
case "B": return PieceType.Bishop;
case "Q": return PieceType.Queen;
case "K": return PieceType.King;
case "P": return PieceType.Pawn;
case "-": return PieceType.None;
default: throw new Error("Invalid piece.")
}
}
return {
type: getPiece(props.type),
position: {row: props.row, col: props.col}
}
}
})
</script>
When I import the component into another component (the component equals Piece):
<script lang="ts">
import { defineComponent } from '#vue/composition-api';
import { Piece } from "../components/Piece";
export default defineComponent({
components: [Piece],
props: {
},
setup() {
const board =
[
['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'],
['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'],
['-', '-', '-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-', '-', '-'],
['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'],
['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R']
];
return { board }
}
})
</script>
I get the following error:
Syntax Error: TypeError: Cannot read property 'kind' of null
Occurred while linting > .\components\Piece.vue:39
at Array.forEach (<anonymous>)
at Array.forEach (<anonymous>)
# ./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader-v16/dist??ref--0-1!./src/components/Board.vue?vue&type=script&lang=ts 3:0-44 6:15-20
# ./src/components/Board.vue?vue&type=script&lang=ts
# ./src/components/Board.vue
# ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader-v16/dist??ref--0-1!./src/App.vue?vue&type=script&lang=js
# ./src/App.vue?vue&type=script&lang=js
# ./src/App.vue
# ./src/main.js
# multi (webpack)-dev-server/client?http://192.168.3.235:8080&sockPath=/sockjs-node (webpack)/hot/dev-server.js ./src/main.js
The error is occurring at the line:
case "R": return PieceType.Rook
I noticed that if I get rid of the Enum and replace it with strings then it works, but I don't see why the Enum isn't working. The error isn't showing up in my intellisense in vscode and I'm not using the component in a for loop anywhere to trigger the "Array.ForEach" in the error. Any help would be appreciated!
My issue was I didn't run "vue add typescript" to add typescript to the project. I had other issues with how I declared the components, but that was ultimately the issue.

How to fetch the action value from AWS policy document and store it as list?

I need to fetch "Action" values from the AWS policy document.
In some policies, the action values are having a list of values(like Policy 1) and in some policies, the action is having a single value which is a string (like Policy 2).
What I need is:
I want to get the action value from the policy and store it as a list.
(Here, Policy 1 is giving expected output but policy 2 is failing.)
Policy 1:
document_values:
[{'Version': '2012-10-17', 'Statement': [{'Sid': 'VisualEditor0', 'Effect': 'Allow', 'Action': ['iam:CreateInstanceProfile', 'iam:DeleteInstanceProfile', 'iam:GetRole', 'iam:GetInstanceProfile', 'iam:GetPolicy', 'iam:ListGroupPolicies', 'iam:GetAccessKeyLastUsed'],'Resource': ['arn:aws:iam::*:policy/*','arn:aws:iam::*:instance-profile/*']}, {'Sid': 'VisualEditor1', 'Effect': 'Allow', 'Action': ['iam:ListPolicies', 'iam:ListRoles', 'iam:ListGroups'],'Resource': '*'}]}]
Output - Policy 1:
['iam:CreateInstanceProfile', 'iam:DeleteInstanceProfile', 'iam:GetRole', 'iam:GetInstanceProfile', 'iam:GetPolicy', 'iam:ListGroupPolicies', 'iam:GetAccessKeyLastUsed','iam:ListPolicies', 'iam:ListRoles', 'iam:ListGroups']
Policy 2:
document_values:
[{'Version': '2012-10-17', 'Statement': [{'Sid': 'VisualEditor0', 'Effect': 'Allow', 'Action': 'sts:AssumeRole', 'Resource':'*"}]}]
Output-Policy2:
['s', 't', 's', ':', 'A', 's', 's', 'u', 'm', 'e', 'R', 'o', 'l', 'e']
Expected output from policy2:
['sts:AsseumeRole']
Python-Code:
I'm executing the same code for both the policies.
inline_services = [j for i in [i['Action'] for i in document_values[0]['Statement']] for j in i]
print(inline_services)
How to fetch the action value from the policy document irrespective of string or list..?
Instead of writing long list comprehension, you could just create simple function:
p1 = [{'Version': '2012-10-17', 'Statement': [{'Sid': 'VisualEditor0', 'Effect': 'Allow', 'Action': ['iam:CreateInstanceProfile', 'iam:DeleteInstanceProfile', 'iam:GetRole', 'iam:GetInstanceProfile', 'iam:GetPolicy', 'iam:ListGroupPolicies', 'iam:GetAccessKeyLastUsed'],'Resource': ['arn:aws:iam::*:policy/*','arn:aws:iam::*:instance-profile/*']}, {'Sid': 'VisualEditor1', 'Effect': 'Allow', 'Action': ['iam:ListPolicies', 'iam:ListRoles', 'iam:ListGroups'],'Resource': '*'}]}]
p2 = [{'Version': '2012-10-17', 'Statement': [{'Sid': 'VisualEditor0', 'Effect': 'Allow', 'Action': 'sts:AssumeRole', 'Resource':'*'}]}]
def get_actions(policy_doc):
actions_list = []
for i in policy_doc[0]['Statement']:
actions_list += i['Action'] if isinstance(i['Action'], list) else [i['Action']]
return actions_list
print(get_actions(p1))
print(get_actions(p2))
Output:
['iam:CreateInstanceProfile', 'iam:DeleteInstanceProfile', 'iam:GetRole', 'iam:GetInstanceProfile', 'iam:GetPolicy', 'iam:ListGroupPolicies', 'iam:GetAccessKeyLastUsed', 'iam:ListPolicies', 'iam:ListRoles', 'iam:ListGroups']
['sts:AssumeRole']

Flask TypeError: argument of type 'NoneType' is not iterable

I am not sure why I am getting this TypeError:
File "C:/Users/PycharmProjects/REST/app.py", line 30, in
valid_book_object
if ("isbn" in book and "name" in book and "price" in book):
TypeError: argument of type 'NoneType' is not iterable
127.0.0.1 - - [12/Nov/2018 14:22:29] "POST /books HTTP/1.1" 500 -
Code:
from flask import Flask, jsonify, request
from test import *
app=Flask(__name__)
books=[
{'name': 'M',
'price': 6.75,
'isbn':123
},
{'name': 'G',
'price': 7.75,
'isbn':456
},
]
#GET /store
#app.route('/books') #first endpoint
def get_books():
return jsonify({'books': books})
# POST /books
#{'name': 'F',
#'price': 7.00,
#'isbn': 789
#},
def valid_book_object(book):
if ("isbn" in book and "name" in book and "price" in book):
return True
print("true")
else:
return False
print("false")
#app.route('/books', methods=['POST'])
def add_book():
#return jsonify(request.get_json())
request_data=request.get_json()
if(valid_book_object(request_data)):
books.insert(0, request_data)
return "True"
else:
return "False"
#GET /books/456
#app.route('/books/<int:isbn>') #second endpoint
def get_book_by_isbn(isbn):
return_value={}
for book in books:
if book["isbn"]==isbn:
return_value={
'name': book["name"],
'price':book["price"]
}
return jsonify(return_value)
app.run(port=5000)
You are not sending JSON data to /books route using POST method.
I tried your solution with postman and it worked. Also, if you want to use some route for GET and POST, don't split them. Use methods=['GET', 'POST']. Here is your code reformatted with PEP 8 standard:
from flask import Flask, jsonify, request
app = Flask(__name__)
books = [
{'name': 'M',
'price': 6.75,
'isbn': 123
},
{'name': 'G',
'price': 7.75,
'isbn': 456
}
]
# POST /books
# {
# "name": "F",
# "price": 7.00,
# "isbn": 789
# }
def valid_book_object(book):
if "isbn" in book and "name" in book and "price" in book:
return True
else:
return False
#app.route('/books', methods=['GET', 'POST'])
def add_book():
# If request is GET, just return JSON data of books.
if request.method == 'GET':
return jsonify({'books': books})
else:
# This is part if it is POST request
request_data = request.get_json()
if valid_book_object(request_data):
books.insert(0, request_data)
return "True"
else:
return "False"
# GET /books/456
#app.route('/books/<int:isbn>') # second endpoint
def get_book_by_isbn(isbn):
return_value = {}
for book in books:
if book["isbn"] == isbn:
return_value = {
'name': book["name"],
'price': book["price"]
}
return jsonify(return_value)
return 'No book with {} isbn value'.format(isbn)
if __name__ == '__main__':
app.run(port=5000)
And here is the output from postman (you can see True at the bottom, that is what you return if POST was successful):
If you use postman, be sure to select application/json content-type.
If you are using JQuery ajax method, please read this answer. But anyway, here is using JQuery (tested):
data = JSON.stringify({
name: "F",
price: 7.00,
isbn: 789
});
$.ajax({
url: '/books',
type: "POST",
data: data,
contentType: "application/json",
dataType: "json",
success: function(){
console.log('Post executed successfully');
}
})

Python nested json to csv

I can't convert this Json to csv. I have been trying with different solutions posted here using panda or other parser but non solved this.
This is a small extract of the big json
{'data': {'items': [{'category': 'cat',
'coupon_code': 'cupon 1',
'coupon_name': '$829.99/€705.79 ',
'coupon_url': 'link3',
'end_time': '2017-12-31 00:00:00',
'language': 'sp',
'start_time': '2017-12-19 00:00:00'},
{'category': 'LED ',
'coupon_code': 'code',
'coupon_name': 'text',
'coupon_url': 'link',
'end_time': '2018-01-31 00:00:00',
'language': 'sp',
'start_time': '2017-10-07 00:00:00'}],
'total_pages': 1,
'total_results': 137},
'error_no': 0,
'msg': '',
'request': 'GET api/ #2017-12-26 04:50:02'}
I'd like to get an output like this with the columns:
category, coupon_code, coupon_name, coupon_url, end_time, language, start_time
I'm running python 3.6 with no restrictions.

Resources