I'm getting a KeyError while using the JSON library in Python (with Flask)
I don't really understand it.
KeyError: 'sites'
is the error I'm getting
JSON Code:
{
"sites": {
"example-site": {
"domains": [
"example.pagehost.com",
"127.0.0.1:5000"
],
"pages": {
"index/": "index.html"
},
"index": "index.html",
"owner": "Bevan",
"id": "example-site"
}
}
}
Python Code:
global sites_json
fsite = ""
print("Finding site")
for site in sites_json['sites']:
for domain in site['domains']:
if domain == host:
fsite = site
print("Found site")
break
The infringing line appears to be the for site in sites_json['sites']
May someone who knows what is going on please help?
After some messing around, it turns out that I was launching my Flask app through the python3 -m flask run command, which skipped my JSON file's initialisation steps. When I launch through the python3 app.py command, it works correctly!
Related
I have to implement a web service using Flask and MongoDB. I have two collections. The JSON files are shown below:
File products.json:
{ "name":"red apples", "price":0.5, "description":"Apples from Greece", "category":"fruits", "stock":25 }
{ "name":"fish", "price":5, "description":"Fresh fish", "category":"fish", "stock":25 }
{ "name":"pasta", "price":1.5, "description":"Pasta from Italia", "category":"pasta", "stock":25 }
File users.json:
{"name":"George Vaios", "password":"321", "email":"george#gmail.gr", "category":"admin"}
{"name":"Admin", "password":"admin", "email":"admin#gmail.gr", "category":"admin"}
What I'm trying to do?
I'm trying to implement a function called add_product. This function allows users whose category is admin ("category": "admin"). As a route has a POST method because I'm parsing the email of a user and the details are needed to import a new product in products.json.
Code:
(lines of code for loading data)
user = users.find_one({"email":data['email']})
if (user['category']=="admin"):
product = {
"name": data['name'],
"price": data['price'],
"description": data['description'],
"category": data['category'],
"stock": data['stock']
}
products.insert_one(product)
return Response("Product was added succesfully", status=200, mimetype='application/json')
else:
return Response("Account has no permission. Must be an admin", status=400, mimetype='application/json')
With that code I'm trying to check if the user is an admin by finding him in the JSON file using the find_one method and then compare the user['category'] with the string 'admin'.
Data that I'm parsing to postman:
{
"email": "george#gmail.gr",
"name": "chocolate",
"price": 25,
"description": "mklkgj",
"category": "sweets",
"stock": 30
}
Error that I get:
File "/home/michael/main.py", line 241, in add_product_admin
if (user['category']=="admin"):
TypeError: 'NoneType' object is not subscriptable
I can't understand why the if statement doesn't make the comparison. Any thoughts?
Mongo is telling you that nothing came up when searching for that value. I would start by checking if data['email'] has the value you would expect and if your collection is initialized correctly.
Thanks to everyone who explained to me what's going on. The actual problem was on MongoDB and client parameters on Python script. That's why the entries and JSON files were unreadable. If anyone comes up again with this problem be sure that you have checked:
# Choose database
database = client['database you want to access']
Then don't forget to check with mongo shell if your expected collections exist:
db.(your database name).find({})
Thank you for your time!
I need to update python script to work with additional data which are not there at the moment. Hence the use of "requests" but somehow it's not working for me.
Basically I need python version of below curl which is providing data I need e.g.:
curl -X GET -H "Authorization: GenieKey XXXXXXXXXXXXXXX" 'https://api.eu.opsgenie.com/v2/alerts/f013a45e-4227-44bb-a0a7-9b2cb6c7c2d9-1616676741714?identifierType=id'
{
"data":{
"seen":true,
"id":"f013a45e-4227-44bb-a0a7-9b2cb6c7c2d9-1616676741714",
"tinyId":"400",
"alias":"test MP",
"message":"MP testing",
"status":"open",
"acknowledged":true,
"isSeen":true,
"tags":[
"MP testing",
"sre"
],
"snoozed":false,
"count":1,
"lastOccurredAt":"2021-03-25T12:52:21.714Z",
"createdAt":"2021-03-25T12:52:21.714Z",
"updatedAt":"2021-04-16T10:28:18.372Z",
"source":"mail#mail.no",
"owner":"mail#mail.no",
"priority":"P5",
"teams":[
{
"id":"45c719c5-d3e1-4e75-9284-b0c75103d44a"
}
],
"responders":[
{
"type":"team",
"id":"45c719c5-d3e1-4e75-9284-b0c75103d44a"
}
],
"integration":{
"id":"132f80a5-b653-4b8a-ba33-eed59cfd6a0a",
"name":"Default API",
"type":"API"
},
"report":{
"ackTime":1892156658,
"acknowledgedBy":"mail#mail.no"
},
"ownerTeamId":"45c719c5-d3e1-4e75-9284-b0c75103d44a",
"actions":[
],
"entity":"TEST MP",
"description":"popis problemu {{priority}}",
"details":{
"priority2":"jednicka",
"issueKey":"FIXIT-981939"
}
},
"took":0.005,
"requestId":"b1f0f485-b06e-45f2-88c0-fe5809cd1ea9"
}
Part of the python script I need to create looks like this for now:
import requests
from requests.auth import HTTPBasicAuth
# Making a get request
response = requests.get('https://api.eu.opsgenie.com/v2/alerts/f013a45e-4227-44bb-a0a7-9b2cb6c7c2d9-1616676741714?identifierType=id', auth=('Correct ID', 'Correct PW'))
print(response.text) # To print unicode response string
print(response)
Result I am getting:
root#server: pts/0: 2 files -> python3 get_request2.py
<Response [422]>
{
"message":"Key format is not valid!",
"took":0.001,
"requestId":"cc21637d-c864-4ba0-92a6-e454ddb74663"
}
Can you please help to determine why I am not getting the data as it is working from shell via curl? I tried to find similar topics but no solution for working for me. I tried add headers or verify=False but no success. Sensitive info is hidden.
Source data are in JSON if it matters and python version is 3.4.10
Thank you in advance for any advice
I am working on django-rest-framework site and keep getting and error with the index.js file. I've tried adding the .mjs file extension and changing package.json but nothing has fixed this error. VS code gives me the error of 'App is declared but its value is never read ts(6133). I run the python manage.py runserver and then the npm dev server command and I do not have any errors yet I am still not able to get the site to render some of the values in the console properly.
I am new to programming so please forgive my ignorance as I pretend to know something about what I am talking about here.
Here is my index.js file
import App from "./components/App";
This is the App.js file
import React, { Component } from "react";
import { render } from "react-dom";
import HomePage from "./HomePage";
export default class App extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<HomePage />
</div>
);
}
}
const appDiv = document.getElementById("app");
render(<App />, appDiv);
package.json file
{
"name": "frontend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "webpack --mode development --watch",
"build": "webpack --mode production"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#babel/core": "^7.12.10",
"#babel/preset-env": "^7.12.11",
"#babel/preset-react": "^7.12.10",
"babel-loader": "^8.2.2",
"webpack": "^5.11.0",
"webpack-cli": "^4.2.0"
},
"dependencies": {
"#babel/plugin-proposal-class-properties": "^7.12.1",
"#material-ui/core": "^4.11.2",
"#material-ui/icons": "^4.11.2",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-router-dom": "^5.2.0"
}
}
Any help is very much appreciated!
That's just a lint. It's telling you that in index.js, you have declared a variable (App), and not used it. Bad programming practice, so your linter (I think VSCode lints JS by default, or maybe you have installed a linter like ESLint) is telling you that. The 6133 number is the error number in the linter.
I'm trying to host the Swagger UI of Flask Restplus on Heroku server. It builds successfully and when checked in the logs of the heroku, even there it says "Build succeeded".
But the problem is when I check the actual hosting there's just a msg on the page saying
No API definition provided.
Btw the swagger-UI loads successfully on the browser when run locally.
Following is a sample code snipet for swagger-ui
from flask import Flask
from flask_restplus import Resource, Api
import os
app = Flask(__name__)
api = Api(app)
#api.route('/hello')
class HelloWorld(Resource):
def get(self):
return {'hello': 'world'}
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
app.run(host="0.0.0.0", port=port, debug=True)
So what am I doing wrong here? Is there any way that you can host a simple minimal flask_restplus swagger-UI on heroku ? Any help is appreciated, thanks.
EDIT
Following is the content of the swagger.json
{
"swagger": "2.0",
"basePath": "/",
"paths": {
"/hello": {
"get": {
"responses": {
"200": {
"description": "Success"
}
},
"operationId": "get_hello_world",
"tags": [
"default"
]
}
}
},
"info": {
"title": "API",
"version": "1.0"
},
"produces": [
"application/json"
],
"consumes": [
"application/json"
],
"tags": [
{
"name": "default",
"description": "Default namespace"
}
],
"responses": {
"ParseError": {
"description": "When a mask can't be parsed"
},
"MaskError": {
"description": "When any error occurs on mask"
}
}
}
Also if it helps, this is what's inside the Procfile
web: python app.py
Posting what worked for me, just in case if someone has the same concern in future.
I changed the Procfile from
web: python app.py
to
web: gunicorn app:app
and then the swagger-UI first page also started showing up on heroku. Earlier the endpoints were still accessible but the first page ie. the swagger-UI page wasn't showing up. But making this change got it working.
I am looking for a python program which will run the URL. Simple, it just needs to run the URL produced from the application with provided credentials to access the application. I will schedule to run the python script every night.
I have an application that produces the URL. If I run that URL, it will produce the JSON file.
I am trying to pre-cache the output of the application so I want to run the URL every morning.
Below are the information:
USERNAME = "test"
PASSWORD = "test5"
HOST = 'appl.xyz.net'
PORT = 8080
Sample URL is:
http://appl.xyz.net:8080/app/content/pq/doQuery?solution=nd&path=&file=Test.nd&dataAccessId=1¶mid=4221
JSON:
{
"queryInfo":{
"totalRows":"3"
},
"resultset":[
[
4215,
null,
"AAA"
],
[
4215,
null,
"BBB"
]
],
"metadata":[
{
"colIndex":0,
"colType":"Numeric",
"colName":"id"
},
{
"colIndex":1,
"colType":"String",
"colName":"Name"
},
{
"colIndex":2,
"colType":"String",
"colName":"City"
}
]
}
Thanks
Use the python-requests library.
Then all you need to do is:
import requests
url = 'http://appl.xyz.net:8080/app/content/pq/doQuery?solution=nd&path=&file=Test.nd&dataAccessId=1¶mid=4221'
user = 'test'
password = 'test5'
# Takes care of the HTTP authentication
data = requests.get(url, auth=(user, password))
json_data = data.json()
StvnW has provided a link in the comments to CURL alternative in Python if you do not wish to install any other libraries.