I have a FastAPI web app, where I would like to use a templating language.
Right now, in order to use jinja2 I have to indicate where the templates folder is located by setting a templates variable like this:
templates = Jinja2Templates(directory="templates")
I also have several view files for various pages and purposes, like home.py, about.py, db.py etc.
If I set up a templates variable once in main.py and then import it into view files like this:
from main import templates
I get all kind of circular import errors. So I have to set up a templates variable in every view file separately which is not optimal.
How can I set templates location once in the main.py and then make all view files aware of this location?
There are many ways you can solve this - move the template configuration to a separate file instead of having it in main (templating.py or define it in __init__.py in your views directory) so that you can import it from that module instead. A plain import would work in that case.
You can also use the dependency injection feature in FastAPI to inject the templating context in a view function.
Set it up as a Depends construct in a separate file (dependencies.py, app_services.py, __init__.py or wherever):
def get_templates():
return Jinja2Templates(directory=...)
And then in your views:
from dependencies import get_templates
...
#router.get('...')
async def display_xyz(templates: Jinja2Templates = Depends(get_templates))
Related
I am currently using next.js framework. Is it possible to route components out of /pages directory?
Would not like to use 'react-router' (because it'll be complicated to edit server.js). If it is inevitable I will but is there any other way?
im afraid this is not possible in nextjs. nextjs builds its route view pages folder. what you can do that wont ruin your project structure or URLs is to
add your components to the new repo.
create your pages folder based on your routes in pervious project.
add index.js in each pages folder.
and import the main component instead of actually moving it to pages folder, for example:
export { default } from './components/users';
this way you can drag and drop your existing structure and only add your route as pages folders.
notes to consider:
next default routing is case sensitive so be careful about your folder names if you want a work around for that you should use nextjs v12 create all pages to lower case and config your project to translate all routes to lower case.
you can have nested routes by adding nested folder:
pages
userslist
userdetail
index.js
this structure will create this route:
/userlist/userdetail
if you have components you dont want for user to be accessible do not put them in pages
if you have dynamic routes such as id in your route you can specify it by adding a folder in pages like [id] and redirect to it following this syntax
Router.push(`/sth/sth/${sth.id}`);
this configuration of redirects in nextjs might come in handy when you need to custom your links
i should also warn you migrating an existing project to nextjs requires a lot of work and a lot of changes to the project.
I have a file called src/services/data.json which I use to populate some data for one of my services. I use the following
import embeddedData from "./data.json";
to import the file. When I generate the distribution, as expected the contents are merged in so they're not in the resulting dist folder
Is there something I can do to the webpack configuration so it will export JSON data files? (I'm using vue with TypeScript for my framework)
I would go with Dynamic Imports. Webpack will create separate files for such imports by default. In runtime those files are asynchronously loaded. Webpack
transforms import() calls to Promises so you can use await/async as well.
I have three questions, but related, and I not getting how can I split them well. I've found many information about those issues, like submodule extension, hierarchy, about an empty __init__.py file, and how to cythonize multiple pyx files. But when I try them together I cannot make them work.
I've prepared an small repo thinking in place together code samples of issues solved. I've check even the code of some of the projects listed that uses cython, but still not getting how to does three things at the same time.
Empty __init__.py file:
In a project (where all the files are pyx (and pxd ifneedbe)), with a __init__.pyx that includes all of them, when there is a __init__.py file, then import it doesn't load the ".so" but the empty init.
cythonize multiple files:
When instead of prepare a __init__.py that includes all the elements of a module. Like:
cythonize(['factory.pyx', 'version.pyx'])
the resulting ".so" import raises an exception:
>>> import barfoo
(...)
ImportError: dynamic module does not define init function (PyInit_barfoo)
It would be related with the previous question if it is necessary to write something in __init__.py.
Submodule:
In fact, this is the main question. The singleton.pyx would part of a submodule, lets say utils to be used from other elements in the module.
For the sample there is a submodule (simply called subm) added in the setup.py as another extension. I've placed earlier than the main one (I don't know if this really does any difference, I didn't see it).
>>> import barfoo
>>> import barfoo.subm
(...)
ImportError: No module named 'barfoo.subm'
Separately, those recipes work, but together I cannot. The "__init__.py" seems to be necessary when there is a mix of "py" and "pyx" files. The examples explain how to cythonize with multiple files, but don't include the last key point for the import. And the submodules doesn't complete about how they can be imported from one place or another (import submodules when import the base one, or optional imports when they are specified).
Thanks to the comments from oz1 and DavidW, I've got the solution. Yes, those three things come together.
Very important is the order when import in the setup.py. Even the PEP8 doesn't say that the imports should be alphabetically sorted, there are other guide lines (like reddit's) that does and I usually follow:
When import first cythonize and then setup, will cause that when cythonize(find_pyx()) is called, the result will be a list of distutils.extension.Extension objects.
from setuptools import setup, find_packages
from Cython.Build import cythonize
setuptools must be imported before cython and then the result of cythionize() will be a list of setuptools.extension.Extension objects that can be passed to the setup() call.
Important to understand the meanings of the __init__'s:
All the __init__.pyx files with includes has been removed and each .pxy file produces its own .so binary.
The main module and the submodules will exist as long as their directories contain the __init__.py file like happen with a pure python code.
In the example I've linked, the file barfoo/__init__.py is not empty because I want that import barfoo provides access to elements like version() or Factory(). Then, this __init__.py is who imports them like a normal pure python.
For the submodule:
Similar for the submodule and its own __init__.py file. In this example the import barfoo will do a from .factory import Factory, who will call from barfoo.subm import Bar, then the subm will be available.
But if the submodule is not imported in this secondary way, the user will have access to it with calls like import barfoo.subm.
Last night I saw your question, and made a simple example according to the wiki. But that question was deleted quickly.
Here is the example: https://github.com/justou/cython_package_demo
Make sure the settings of C compiler and python environment is correct, compile the pyx files by run:
python setup.py build_ext --inplace
Usage is the same as python package:
from dvedit.filters import flip, inverse, reverse
flip.show() # print: In flip call Core function
inverse.show() # print: In inverse call Core function
reverse.show() # print: In reverse call Core function
BTW, there is no need to create an __init__.pyx, you can do the ext_module importings in the __init__.py file
I'm new to Django, and I'm pretty sure I've read or heard about a way to do this, but I can't find it anywhere.
Rather than sending the rendered output from a template to a browser, I want to create an html file that can then be served without the need to go through the rendering process every time. I'm developing on a system that's separate from our main website's server, and I need to make periodic snapshots of my data available to our users without giving them access to the development system.
My intuition says that I should be able to somehow redirect the response to a file, but I'm not seeing it in the docs or in other posts here.
You can leverage Django's template loader to render your template, including whatever context you pass to it, as a string and then save that out to the filesystem. If you need to save that file on an external system, such as Amazon S3, you can use the Boto library.
Here's an example of how to render a view to a file, using an optional querystring parameter as the trigger...
from django.shortcuts import render
from django.template.loader import render_to_string
def my_view(request):
as_file = request.GET.get('as_file')
context = {'some_key': 'some_value'}
if as_file:
content = render_to_string('your-template.html', context)
with open('path/to/your-template-static.html', 'w') as static_file:
static_file.write(content)
return render('your-template.html', context)
django-bakery is a well-developed "set of helpers for baking your Django site out as flat files".
There's a well developed Django app specifically for this: django-render-static
This is my first time working with Django and while I'm finding the tutorial they provide to be very helpful, there is one major issue I'm having moving forward with my project.
The most confusing aspect of Django so far is the layout of files in a project. As of now, the layout of my project is as follows:
webapp/
manage.py
mysite/
__init__.py
settings.py
urls.py
wsgi.py
app/
__init__.py
models.py
tests.py
views.py
Bear with my naming here, I created a Django project "mysite" and an app "app". Here are the questions I find myself continually returning to:
I've noticed that in mysite/settings.py there is a section for apps, would I include the app I'm writing in this project in that section once I've finished it?
If I were to want to create a simple index.html page, where would a file like that go in this project organization?
I've read that static content like CSS or image files need to be contained within a simple "static" directory. Where would this go in this project organization? [ This would be for debugging purposes only, I've read this should never be done for production ]
My main goal right now is to just be able to view a simple html site before I begin delving into the models and views of the app I'm creating.
If your app needs one or more setting variables, then yes, you would put those in mysite/settings.py
Create a new folder mysite/templates/. This is where you want to put your template files. Organize your templates per app: mysite/templates/app/ would have the templates used by your app views. If you want to serve static templates such as a simple static index.html, then just throw that file in mysite/templates/index.html and then add the following to your urls.py file (no need to create a view for the index):
(r'^$', 'django.views.generic.simple.direct_to_template', {'template': 'index.html'}),
Static content would end up in something like mysite/static after you run the collectstatic command. See managing static files. The collectstatic command searches for static files in all locations specified in STATICFILES_DIRS and deploys them into the folder specified in STATIC_ROOT (mysite/static).