In my Django project I have the following directory structure:
project/build/contracts/MyFile.json
And I am writing code in the following directory
project/homeapp/views.py
In my views.py I have the following code:
with open("../build/contracts/MyFile.json", "r") as f:
data = json.loads(f.read())
abi = data["abi"]
When I try to python manage.py runserver I get the following error:
The strange part is that I couldn't figure out what was wrong so I made a viewstest.py and placed the exact same code in it. When I run it with python .\viewstest.py and print the JSON to console, it works perfectly fine.
I even tried importing the abi variable from viewstest.py to views.py but got the same error. So I assume that it is an error relating to Django, but I can't seem to figure it out.
Thanks!
It should be json.load() and not json.loads()
Change the following code to:
with open("../build/contracts/MyFile.json", "r") as file:
data = json.load(file)
abi = data["abi"]
Edit:
Another alternative to get the path correct can be to use Pathlib.
from pathlib import Path
def your_view_func(request):
current_dir = Path.cwd()
file_loc = 'build/contracts/MyFile.json'
with open(current_dir.joinpath(file_loc), 'r') as file:
data = json.load(file)
abi = data["abi"]
Related
I have made a config file named "config.cfg" that's on the same folder of my .py file.
My config file is like this:
[NetAccess]
host=localhost
port=3306
[Credentials]
username=myuser
password=mypass
[Database]
name=mydb
in my .py file I have this code:
import configparser
config = configparser.ConfigParser()
config.read('config.cfg')
__DBMSuser = config.get('Credentials', 'username')
__DBMSpsw = config.get('Credentials', 'password')
When I launch my program, I receive this error:
configparser.NoSectionError: No section: 'Credentials'
Can someone help me?
I've solved it. My code was correct, and the .cfg file was correctly saved in the folder of my program, but because of other parts of my code, my current directory changed to "C:/Windows/Service32". Not reading the file, I had not error until I was trying to read the sections, so I got NoSectionError.
To solve it, I've choice a standard folder (in AppData) where to save my file and read it and then I've used the absolute path.
Your code is working for me. Most likely the issue is reading the config file itself. Config Parser's read method is configured to fail silently if it fails to find or read the file, but the read function returns a read_ok boolean flag. Use it to check if the read was successful:
import configparser
config = configparser.ConfigParser()
filename = 'config.cfg'
read_ok = config.read(filename)
if read_ok:
__DBMSuser = config['Credentials']['username']
__DBMSpsw = config['Credentials']['password']
else:
print(f'Could not read file {filename}')
There is no mistake in your code, cuz it works for me.
I think there is some small error with file:
Make sure your file is in same directory as python file
Have you saved your file? maybe you forgot to press ctrl+s
If even that's not working for you, try another version of Python
I am trying to load a JSON file into python with the following code:
import json
def find_case(tag):
with open("C:\\Users\\brend\\Documents\\File Organiser\\Files\\.filepaths\\" + tag + ".json", "r") as f:
filepaths_dict = json.load(f)
This seems to work fine withing PyCharm but crashes immediately on the above line. Can anyone tell me what is causing this and how to fix it?
first of all sorry for my English. I have an Azure Function Linux Consuption Plan using Python and I need to generate an html, transform to pdf using wkhtmltopdf and send it by email.
#generate temporally pdf
config = pdfkit.configuration(wkhtmltopdf="binary/wkhtmltopdf")
pdfkit.from_string(pdf_content, 'report.pdf',configuration=config, options={})
#read pdf and transform to Bytes
with open('report.pdf', 'rb') as f:
data = f.read()
#encode bytes
encoded = base64.b64encode(data).decode()
#Send Email
EmailSendData.sendEmail(html_content,encoded,spanish_month)
Code is running ok in my local development but when I deploy the function and execute the code I am getting an error saying:
Result: Failure Exception: OSError: wkhtmltopdf reported an error: Loading pages (1/6) [> ] 0% [======> ] 10% [==============================> ] 50% [============================================================] 100% QPainter::begin(): Returned false Error: Unable to write to destination
I think that error is reported because for any reason write permission is not available. Can you help me to solve this problem?
Thanks in advance.
The tempfile.gettempdir() method returns a temporary folder, which on Linux is /tmp. Your application can use this directory to store temporary files generated and used by your functions during execution.
So use /tmp/report.pdf as the file directory to save temporary file.
with open('/tmp/report.pdf', 'rb') as f:
data = f.read()
For more details, you could refer to this article.
Final correct code:
config = pdfkit.configuration(wkhtmltopdf="binary/wkhtmltopdf")
local_path = os.path.join(tempfile.gettempdir(), 'report.pdf')
logger.info(tempfile.gettempdir())
pdfkit.from_string(pdf_content, local_path,configuration=config, options={})
Pretty much the title. I tried the code on my local computer and it was fine but when in deployment (Phusion Passenger) this doesn't seem to work.
from flask import Flask
import flask
import json
import os
app = Flask(__name__)
#app.route('/mods')
def mods_index():
try:
reader = app.open_resource(os.path.join(app.root_path , 'static', 'data', 'modifications.json'))
modifications = json.load(reader)
reader.close()
except:
flask.abort(500)
return flask.render_template('mods_index.html', mods=modifications)
I believe this is a file path issue, specifically this line: reader = app.open_resource(os.path.join(app.root_path , 'static', 'data', 'modifications.json')) doesn't look correct.
According to Flask's documentation: app.open_resource(...) "Opens a resource from the application’s resource folder". In your code you're specifying the application's root path twice:
First with app.open_resource(....)
Then again with: app.root_path
So your server is attempting to open your modifications.json file from: <app_root_path>/<app_root_path/static/data/modifications.json as opposed to <app_root_path>/static/data/modifications.json where <app_root_path> is your application's root directory. So the solution is to get rid of one of those double <app_root> mentions. Maybe you could try the following:
reader_path = os.path.join('static', 'data', 'modifications.json'))
with app.open_resource(reader_path) as f:
contents = f.read()
# do_something_with(contents)
Hopefully that helps!
I am working through an online python course and have an issue that I am having trouble working through. I have a executable directory with the following layout
reader/
|--__main__.py
|--reader
|--__init__.py
|--reader.py
|--compressed
|--gzipped.py
|--bzipped.py
|--__init__.py
When I do not have these modules in the top directory, I can import just fine and use all of the functionality. When I put them in the top level directory and run the executable directory from the command line with
python reader test.gz
I am getting the following error
AttributeError: module 'reader' has not attribute 'Reader'
The code for main.py is
import sys
import reader
r = reader.Reader(sys.argv[1])
try:
print(r.read())
finally:
r.close()
The code for reader.py is
import os
from reader.compressed import gzipped, bzipped
extension_map = {
'.bz2': bzipped.opener,
'.gz': gzipped.opener,
}
class Reader:
def __init__(self, filename):
extension = os.path.splitext(filename)[1]
opener = extension_map.get(extension, open)
self.f = opener(filename, 'rt')
def close(self):
self.f.close()
def read(self):
return self.f.read()
I can provide the rest of the files if needed. I am using the current distribution of Anaconda. Any help or explanations would be appreciated.
It seems to me that because of your __init__.py file the folder reader is seen as a python module. Thereore your main.py code tries to find the class Reader at the folder level, but you need to look for Reader within reader.py. Can you try changing
r = reader.Reader(sys.argv[1])
to
r = reader.reader.Reader(sys.argv[1])
Also, you have a lot of modules/files/modules called reader, e.g. the class Reader is in reader/reader/reader.py. This I would try to avoid as it can lead to confusion.
When you have multiple modules/modules that are named identically you can often get the namespace into a recursive loop. Also, the Reader class is capitalized.
Like mentioned above, try python reader.reader test.gz
While you are troubleshooting try the tab-complete feature to see if your modules are being loaded properly.