Raise TemplateNotFound(template) jinja2.exceptions.TemplateNotFound: index.html - python-3.x

I am just providing a piece of code here. When i run the whole code its showing Index.html file is not found.
app = Flask(__name__)
CORS(app)
app.url_map.converters['everything'] = EverythingConverter
def render(duplicates, current, total):
env = Environment(loader=FileSystemLoader('template'))
template = env.get_template('index.html')
return template.render(duplicates=duplicates,
current=current,
total=total)
the error is
raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: index.html
My file path is
/My_project
template
/index.html
my_project.py
I ran the program so many times but its writes the same error. Does anyone had some idea?
thanks in advance

According to the Flask documentation your project layout should look something like this:
my_project/
│
├── templates/
│ └── base.html
│
├── static/
│ └── style.css
│
└── app.py
The directory in which you store your templates should be named:
templates/
Instead of:
template/
Don't forget to change references to this directory as well.

Related

Unable to serve react app using actix files crate

I am trying to serve a react frontend using actix server with the following service :
service(actix_files::Files::new("/app", "./react-front").index_file("./react-front/index.html")
And I have the following structure in react-front which is a react app build using npm run build:
react-front/
├── asset-manifest.json
├── favicon.ico
├── index.html
├── logo192.png
├── logo512.png
├── manifest.json
├── precache-manifest.70429bbe96a34ea56e1cb1a6570602b0.js
├── robots.txt
├── service-worker.js
└── static
├── css
│ ├── main.09af38e2.chunk.css
│ └── main.09af38e2.chunk.css.map
└── js
├── 1.e6893027.chunk.js
├── 1.e6893027.chunk.js.map
├── main.dc35c614.chunk.js
├── main.dc35c614.chunk.js.map
├── runtime~main.229c360f.js
└── runtime~main.229c360f.js.map
Visiting /app I am greeted with this, where "Your React App loaded successfully" is the actual text in my index.html and the rest of the files as you can see from the network tab, gets a 404. I have placed this service before any of the routers in my App configuration, and were I to put this service after my routers I would just get this text and a 204 No Content. No more 404 errors for the react js scripts whatsoever.
This leads me to two questions:
1. What effects result from the order in which service for file resources is written for App builder?
2. How can one serve a complete folder such that the browser can obtain all the relevant css and js files necessary to display the react app?
Currently here's how I am dealing with it: I use the crate actix-web-static-files and static-files to embed the contents react-front folder into the final executable and then run it
You can see that this works now. I want to achieve this without using these crates, just actix-files, if possible.
Here's the working code for this :
HttpServer::new(move || {
let generated = generate();
App::new()
.wrap(Cors::permissive())
.route("/book", web::get().to(get_phonebook_handler))
.route("/book/{id}", web::get().to(get_by_id))
.route("/{name}", web::get().to(get_by_name))
.route("/book/{id}", web::delete().to(delete_id))
.route("/book", web::post().to(post_phonebook_handler))
.route("/book/{id}", web::put().to(put_update))
.service(ResourceFiles::new("/", generated))
})
.listen(tcp)?
.run()
.await

React : how to load image outside src and public folders

My project as this kind of structure :
├── api
├── db
│ └── images
├── ui
│ └── public
│ └── src
│ | └── App.js
My app was created using create-react-app so I can't import files outside of src directory, and I do not want these images to be in the public folder : how can I have an img tag :
<img src="db/images/img_1.jpg">
with src getting images on db/images folder, completely outside of react app ?
Thank you for your replies
Another option is to put the image inside of your src and reference it in a react fashion. Consider the following:
├── ui
│ └── public
│ └── src
│ | └── App.js
└── img_1.jpg
app.js
import img from "./img_1.jpg";
then in your render img tag
<img src={img} />
Hoping this might work for you? iirc this will prevent someone from hotloading the image from your public folder.
If there's literally 0 way of moving the images into your react project, the only way I can think is to upload the images somewhere and reference them from a literal link, such as S3
If you just don't want it to reload when you upload a file, you can ignore the folder the files are uploaded to in you webpack config
devServer: {
...
watchOptions: {
ignored: './src/images/**/.*',
},
...
}
The create-react-app package uses a plugin for Webpack called ModuleScopePlugin that causes this behavior
You can use the package customize-cra for override the webpack configs.
The customize-cra has a method to resolve your problem.
removeModuleScopePlugin
or you can eject from create-react-app and remove this config manually at webpack

Node Express CRUD application folder structure

I am using the following folder structure for my express CRUD application. I use it to have ideal manageable code of each file containing not more than 70 lines of code. What are your thoughts on the folder structure?
.
├── bin\
│ └── www
├── common\
│ ├── enums\
│ │ └── logTypesEnum.js
│ └── validators\
│ └── studentNameValidator.js
├── config\
│ └── db.js # config file for database connection
├── models\
│ └── log.js # contains model data for model 'log'
├── routes\
│ ├── log\
│ │ ├── index.js # handles all routes for /log/ endpoints and requires files in the directory and also contains middleware code
│ │ ├── insert.js # handles all routes for /log/insert endpoints
│ │ ├── remove # handles all routes for /log/remove endpoints
│ │ └── exportCSV.js # handles all routes for /log/exportCSV endpoints
│ └── student\
│ ├── index.js
│ ├── insert.js
│ └── remove.js
├── public\
│ ├── javascripts
│ ├── images
│ └── stylesheets
├── views\
│ ├── log\
│ │ ├── index.jade
│ │ ├── insert.jade
│ │ ├── remove.jade
│ │ ├── exportCSV.jade
│ └── student\
│ ├── index.jade
│ └── insert.jade
└── app.js
I am not sure why you decided on the number 70 unless you read somewhere that 70 makes some sort of ideal microservice which your structure does not allow for anyways.
As to the directory structure. I have come to the conclusion that internal directory structures are usually based on the programmer or team leader. It is more of a matter of what makes sense in your head as you see the visual design and implementation of your code.
That said, IMHO, overly complicated or let us say overly structured directory structures in Node and say for instance PHP cause an inordinate amount of moving up and down directory trees in order to access code, classes or just plain functions. Not to mention that it becomes jibberish for those who may come after you to maintain the code.
So use the directory structure you feel at home with. But make it clean and not complicated. Do not try to pigeonhole every aspect of every call and function into a specific 70 line definable directory structure. (again no clue where that number came from).
Clean, simple and sensible.
Those would be the best rules to follow IMHO.
Edit based on OP questions below:
Clarity of code is not defined by the amount of lines. When I test coders, no matter what language they specialize in, put some code up on the screen and ask them to translate that code line for line into plain English. First this actually tests the candidate ability. And second if the code is clear and good, then any other coder should be able to read it and clearly understand what is going on in the code. (Actually it tests both the original coder and the candidate.)
So clear code is not about lines. It is about excellent coding practices and the ability to make your code do what you envision.
Microservices has become sort of a buzzword. But essentially it simply means "focused". It means that you are creating a module to do a specific task So each module in your system does a specific task or tasks essential to your system and only focuses on that task. I think that may be actually what you are striving for. There are quite a few really good articles out there on Node and Microservices.

test or prevent some relative path imports / requires

I have a folder structure like so:
.
└── client
├── components
└── routes
├── index.js
├── Login
│ ├── index.js
│ ├── assets
│ ├── components
│ ├── container
│ └── modules
└── UpdatePassword
├── index.js
├── assets
├── components
├── container
└── modules
I would like to see if anyone is importing files from the UpdatePassword folder to the Login folder and vice versa.
Basically I'm following a fractal project structure where I want components that are related to the UpdatePassword or Login route to only exist in their respective folders. Shared components would exist in the client/components subdirectory. To maintain a structure like this, I would like to write a test that fails when an 'unacceptable' imports or require is used. I.e. if a file in UpdatePassword imports from Login/components.
Is there a way to test or check whether an import is coming from specific folders?
Try madge: I usually run it as madge --image /path-to-folder/dependencies.png routes (There is also a exclude option if you need it)
You'll get a visual graph which shows you dependencies between files.
I have no idea about native way to do it.But you can wrap "require" function:
function myRequire(fromPath, requiredPath) {
//code to judge whether or not can load requiredPath from fromPath
var can = ...
if(can) {
return require(requiredPath);
}
else {
throw new Error(`you can not load ${requiredPath} from ${fromPath}`);
}
}

Cloud9 Node js Express jade IDE: file structure

In Cloud9 Express IDE example I see in folder/file routes/users.js - please tell me why this is in separate file -what is the intention of users.js as a distinct file? :
/*
GET users listing.
*/
exports.list = function(req, res){
res.send("respond with a resource");
};
ok Im trying to answer that one myself (feel free to chime in):
The basic Express set up folder structure according to Expressjs.com looks like this:
├── app.js
├── bin
│ └── www
├── package.json
├── public
│ ├── images
│ ├── javascripts
│ └── stylesheets
│ └── style.css
├── routes
│ ├── index.js
│ └── users.js
└── views
├── error.jade
├── index.jade
└── layout.jade
It is suggested and not obligatory. However for noobs like me this helpful website says:
If you are getting started with Express it is recommended that you use the structure from the generator.
Edited:
In the particular folder structure generated in Cloud9 Express the file /routes/users IS intrinsic to a typical Express-Jade setup.
Basic routing tutorial here answers what each of these files is doing

Resources