Embed Flask page in another without code duplication? - python

I have a page (located at /games/compare/) and it's a mini image comparison game. Users are shown two images and asked to pick between them in response to a question. This page can get images from the database, render a template with javascript and css inside and communicate back to the database using AJAX.
Now what if I wanted to embed this voting game onto the main page without duplicating any code? Ideally, I'd update the game and all the pages that "feature" the game will also reflect the changes.
I'm getting hung up on how to manage the assets for the entire site in a coherent and organized way. Some pages have css, javascript and I'm also using frameworks like bootstrap and a GIS framework.
Would I set the game up as a blueprint? How would I organize the assets (Javascript and CSS) so that there is no duplication?
Currently, I have a page rendering a template (main.html) which extends another (base.html). Base.html includes header.html, nav.html and footer.html with blocks set up for body and others.
My current approach is to strip everything out at the lowest level and reassemble it at a highest common level, which makes coding really slow. For instance, I have that voting game and right now it's located in a page called voting_game.html and has everything in it needed to play the game (full page html, styles and javascript included). Now if I want to include that game on another page, like the root index, the only solution I know of is to strip out the style, js and full page html from voting_game.html, leaving only the html necessary for the game to run. When I'm creating the index now, I'll import the html from voting_game.html but I'll separately have to import the style and javascript. This means I have to build every page twice, which is twice the work I need to be doing. This process also leaves little files all over the place, as I'm constantly refactoring and it makes development just a bookkeeping nightmare.
There has to be a way to do this and stay organized but I need your help understanding the best way to do this.
Thanks,
Phil
Edit: The embedded page should also be able to communicate with its parent page (the one it is being embedded into), or with other embedded pages within the same parent (children of a parent should be able to talk. So when someone plays the embedded game, they earn points, which should show up on another part other page, which would update reflecting the users current points.
This "Score board" would also be a separate widget/page/blueprint that can be embedded and will look for certain pieces of data in order to function.

To re-use a chunk of HTML, you can use Jinja's {% include %} tag. If that's too limiting, Jinja macros are also well suited. You can define your macros in a separate file and import them with {% import "path/to/macros.html" as my_macros %}.
Flask-Assets can help with the organisation of your assets.
As for using Blueprints, yes you should use them. But they mostly apply to Python code and HTML templates are organised in a different realm, so maybe their use is unrelated here.
You can't always remove all duplication though. If your game needs to affect three distant locations of the server-generated HTML, that's bits of template code to copy in every template that includes your game.

Related

How to check current URL/endpoint in django if statement

I have a button on a base template that just takes you back (history.back()) on every page except for one specific page. I assume there's a simple one line like {% if URL == specificURL %} but for the life of me I can't figure out how to do it.
Im trying to do it within the html, but I'll happily take any other suggestions if something else would work
Its a light site and I could take the button off the base template and just put separate logic on every html page but that's obviously bad for scale
should also probably preface that I'm definitely beginner for Django
edit: just thought of using a content block to change the base template in just the one page. Think that should work but I would still like to know if it can be solved my original way as id use that for other purposes

Detect changes in html using Django?

First of all, I'm very very new to web development (a few days), so I might say something that doesn't make sense.
I am writing a music web app using Django and I want to display a piano keyboard, have the user play some keys and then be able to retrieve this data (the notes the user played). I was able to embed the piano thanks to this, but I don't know how to get the data back. I tried wrapping the html key tags (<li class="key">...</li>) within a form tag and a submit bottom but I can't get it to work properly, and I'm not even sure if it's possible this way.
Then I realized, when you press some key, the tag's class changes from class="key" to class="key.active", so I was wondering if there is a way to detect these changes in the .html and thus be able to store the data. Does this even make sense? Maybe write a .py script to read the .html as a string and look for this changes? But does the .html file stored in the server change, or does it only change on the user's browser? I haven't found any info on the matter, which makes me think it might not be possible...

Batch Printing a customized HTML pages in Python

Let me provide a little background.
An organization i am volunteering for delivers meals to people who are unable to come pick them up during the holidays.
They currently have a SQL Server DB that stores the information of all their clients along with the meal information for each year.
Currently a Java desktop application connects to the SQL Server DB and allows several functions to happen.
i.e. Add a client, add meals, remove clients, print delivery sheets.
I am hoping to use python Flask to rewrite the application as a web based application. The one function i am interested in at the moment is the print delivery sheets function.
The way this works is there is a setting for the current year. When you click the print deliveries for year button it will batch print a document for each customer onto an 8.5" x 11.5" paper. The sheet will be split in two with the same exact information on each side. This information includes the customer name, address, number of meals and so forth.
What i am wondering is how/what would be the best way to setup this template so that i could batch print it using python. I was thinking of creating an html template for the page but i am not sure how that would work.
Again i need to pass in every customer within that year into the template and batch print to 8.5" by 11.5" sheet.
What i am asking is.....
How could i create a template for the print that i can pass every customer two.
How would i print that template for every customer in a batch manner for every customer.
I was hoping to do this all in python if possible.
Thank you for your time and help.
If you are already deploying this as a web app, it will probably be easier to design and generate a pdf. You can use an html to pdf converter, which there are several of on PyPI, or there are plenty of resources online, such as:
How to convert webpage into PDF by using Python
https://www.smallsurething.com/how-to-generate-pdf-reports-with-jinja2-and-pyqt/
Once you have found a way to generate PDFs, you can then just use them like any other PDF, and either have the user download them or print them from the browser (this may require a little bit of Javascript, but this shouldn't be that hard since it should pretty much just be a window.open call.
For instance, you can add a button
<button onclick="getPDF()">Download PDF</button>
Which will then call a function called getPDF() which you define, which finds a way to generate the pdf.
function getPDF() {
// Find the uri for the pdf by some method
var urlToPdf = getUrlToPdf();
// Open PDF in new window
window.open(urlToPdf, "_blank");
}
Note Since you are using Flask, you can include the URL for the pdf in the source for the page, even the Javascript using the {{ }} syntax. Then the pdfs are only generated when someone requests that route.
This way you will not have to worry about connecting to a printer yourself at all, just use the browser to handle those kinds of tasks.

Can I Use One view In a Django Project?

I´m new to web dev,
and I was wondering if it´s possible to make a website, that just need to present information of a company (HTML), in just one view.
Like rendering the entire bootstrap in one view.
Yes, you can serve your HTML code through a TemplateView.
So if your entire single page application sits in home.html you could definitely do this. But there is no point in using Django for only that purpose. You would rather want to serve your static HTML page from a classic web server like nginx or apache.
I don't know why would you want to do that.
You can use different html files which will be served as your website templates. You can also extend the files using a simple base.html file. This will help you if you want to open other links when people click on different links on the website.
See this example: https://github.com/singh1114/Djangosite/tree/master/duggal/webportal/templates/webportal.
For using this you have to know more about views and urls.
For making scrollable things, you need to know the concept of ids in HTML.
For example
http://yoursite.com/#your_name will try to find id your_name in the HTML. This way you can create scrollable things.

How to make almost static site in Pyramid?

I'm switching to Pyramid from Apache/PHP/Smarty/Dreamweaver scheme.
I mean the situation of having static site in Apache with menu realized via Dreamweaver template or other static tools. And then if I wanted to put some dynamic content in html I could make the following:
Put smarty templates in html.
Create php behind html with same name. Php takes html as template.
Change links from html to php.
And that was all.
This scheme is convenient because the site is viewable in browser and editable
in Dreamweaver.
How can I reproduce this scheme in Pyramid?
There are separate dirs for templates and static content. Plus all this myapp:static modifiers in hrefs. Where to look up?
Thank you for your advices.
There is no smarty port for Python. So you would have to start using another template syntax, such as mako or chameleon
To do this, you would setup your view_config to respond to the url, end tell it to use the corresponding template.
If you want to do this, you would simple change your code. But this is not necessary, pyramid will process your requests, whether the url contains .html, .php, .python, /, or whatever.
You could still edit the templates in Dreamweaver I guess.
Only really static pages would be linked using static_url. If it is html that you mean to make into a template, it might be easiest to just start of with a template right away, without any dynamic content in it.
This is from the URL dispatch tutorial:
# in views.py
#view_config(route_name='view_page', renderer='templates/view.pt')
def view_page(request):
return {}
# in __init__.py
config.add_route('view_page', 'mypage.html')
You can build a small web application which uses traversal to serve html documents from a directory. Here's more explanations about how traversal works.
Then you can programmatically render those documents as Chameleon templates, using PageTemplateFile for example. This would allow you to include, say, common header/footer/navigation into every page.
This would mean that every page in your site will be in fact dynamic, so that would incur a small performance penalty for every page regardless of whether it has dynamic content or not, but you should not be concerned with this unless you're building the next Facebook. :) However, this approach would allow you to have a plain html document corresponding to every page in your website which you'll be able to edit using Dreamweaver or any other editor.
This is somewhat a different answer than ohters but here is a completely different flow.
Write all your pages in html. Everything!!! and then use something like angularjs or knockoutjs to add dynamic content. Pyramid will serve dynamic content requested using ajax.
You can then map everything to you html templates... edit those templates wherever you want since they are simply html files.
The downside is that making it work altogether isn't that simple at first.

Categories