How to access Models.py from external py script? - python

I want to integrate my existing code into django. How can I access models.py from external code.I tried putting it in the same application directory but it did not work.
Case Scenario: Having a web parsing code that takes data from the web and prints it. Here I am integrating it with django so as to save that data in the db and print it out in the web page. I'm trying the input to get from the webpage and when I hit submit it triggers the parsing code and gives output on the page.
I have the Django server up and running, created the apps (startapp), have the table created via models.py, have the urls.py setup. Here my question is how or where do I put my external code to make it trigger to access models .py, will it execute by itself when I start the server and hit the submit button ( i know i have to configure this one).

There are a few lines you need to include in your script if you want to use Django in "standalone" mode. See the documentation here: https://docs.djangoproject.com/en/1.10/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage .
Another option would be to turn your script into a Django management command which you would then call with manage.py.

Related

How to display user inputted blogs in flask production server

I'm using gunicorn and nginx to serve a flask application, my website has a blogging feature where users can write blogs, once they do, their input is saved as an html file (I use tinyMCE to generate it) and a flask view is added to a views.py file. Now, in deployment, I just used
use_reloader=True
This ensured that every time a new file was added, it was detected, now in production, I don't know how to implement it, gunicorn has --reload option but the docs say that it's only for development. Can someone please provide an insight on how to implement this feature? Thanks!
You don't need a new view for every html file. You could use a generic view that renders the appropriate html according to the url requested.

Django & React with django-webpack-loader vs Decoupled App structure linked to Rest API?

I am reading through the following tutorial:
http://v1k45.com/blog/modern-django-part-1-setting-up-django-and-react/
I can't quite grasp what the added value is of using something like django-webpack-loader to fully integrate react.js and django when you can completely decouple django from react, running a separate frontend which links to a DRF rest api.
I may be comparing apples to oranges here, but I am not sure. Any help ?
From the django-webpack-loader tutorial:
Now that we’ve handed off the build process webpack, only thing we need on the django side is to know which bundle to include in our html pages. This is where django-webpack-loader comes in. It’ll also raise exceptions when webpack fails to build a bundle and will show some useful information to help debug the problem. During development, webpack loader will also block requests while a new bundle is being generated so that only the latest bundles are loaded.
This is the core functionality of that loader. It tells django which are the current bundles to be served. It does not server side render your react app nor does it replace an API that the app needs to consume.
When developing a react app you usually use some kind of bundler that transpiles your javascript code to es5, uglyfies and minifies it. So every time your code changes a new bundle will be created containing your new javascript. A lot of people are using webpack for this task.
Now when a request arrives in django it needs to serve the basic html along with the css and js to be loaded by the client that contains the react app. So django needs to know the path to the files to link. But the path may constantly change when webpack rebuilds them. django-webpack-loader helps you to keep track of these changes and includes the correct paths to the current bundles for your react app to be fetched.
It is not a replacement for an API. Its sole task is to resolve the correct paths to your react app files.
EDIT
So the primary purpose of django-webpack-loader is to ensure that the paths to the most recent build are resolved correctly and in turn can be served. What is the reason these paths will change ?
Weppack appends a random hash to a new bundle like bundle.4j2a032fg.js. This way django can tell the client to cache the script so that it does not have to be re-request it every time. The client will only request a new bundle if the url/path changed. But this also requires that django knows the newest bundle with the correct hash.
does server side rendering occur with the use of Django templates ?
Server Side Rendering (SSR) in the context of react means that a nodejs server actually runs the react application once on the server to produce the initial markup of the app. This can then be statically served with the app. It reduces the perceived loading time for the user because the initial state of the app will immediately be shown and it allows for search engines to statically analyse the page which is good for SEO.
While django does render templates it is only the static html around the react app which it will render by default. Django does not render the react app itself. The react app still needs to initially render itself on the client. So to enable django do do true server side rendering you would have to run a nodejs process next to django that does the static rendering of the react app for django to serve.
In the tutorial they are using templates. Templates are loaded in the backend. So user gets fully rendered page.
With django rest framework you need to write seperate fronend. More about this: https://nickjanetakis.com/blog/server-side-templates-vs-rest-api-and-javascript-front-end

Python-Django module import issue

I have JSON data coming through various external API's into my Django project. I have two apps, one called 'products' and other 'extract'. Through product app, have created the database and rendered the views required. Objective of extract app is to parse the JSON data and create/update the fields in the Django database. I have this code saved in extract/views.py as shown below -
import json
import urllib2
from products.models import Product
url = " .........."
.............
for i in data[results]:
Product.objects.get_or_create (...........)
The issue I am having is this code is working well in python shell. It is extracting all the JSON data and updating the database. But, when I run the script on the command line outside of Python shell, it is giving error - 'Import error: No module named products.models'.
Django requires you to run python manage.py shell in order for the product app's models and Django internals to be initialized.
Check out this blog post by Stavros Korokithakis to convert your code into a standalone script.
I believe the error is with the directory set up. Make sure all your migrations are done as well as the initial folder has the paths to your apps. Possible you need to include the paths to each app in the other's settings.

Django - Privatizing Code - Which files are served to a user?

I am using Django to develop an API using an algorithm I wrote.
When someone requests a url, my urls.py calls a function in views.py which serves
page that returns a JSON string.
If my algorithm is in my views.py file, or in another file on my server, would it be possible for a user to view the contents of this file, and then see my algorithm?
In other words, when using Django, which files will never be served to a user, and which files will be?
Is there any way I can stop someone from viewing my algorithm if it's in a .py file? Other than Chmodding the file or encrypting the code?
Thank you for your time.
Django only serves the responses that you explicitly create and return from your views. There is no general ability to request files from it.
Make sure your source code isn't in a directory that your web server is configured to serve from, and make sure your settings.py value for DEBUG is False, and you should be fine. Oh, and just in case - don't try to use the Django development server in production.
As long as nobody has shell access to your server, people will never see more than the actual HTML output of your page. .py files are not shown to the user that has requested an url in the browser.

integrating python scripts with django

I have written some test scripts in python which call some apis for a paritcular application and output the results to a database so I can use jasper to report on the results. Currently the scripts are run using a python interpreter, ie double click on the python file that has some parameters and variables modifed within the script that then initiates the tests. I would like to move towards a more user friendly interface so other people can use these test scripts without having to modify the python code. So I am thinking about using django and creating a web page that has check boxes, and if the check box is ticked, then it will execute that particular python test script or a text box that will pass the values to a given variable, for example. I have a few questions around how this might be achieved.
1 - would I need to implement the python code in to the django source code or can I call the python script from the web page served up by django?
2 - If I were to run this from a web page, how could I ensure that if the web page was closed, that the test would continue in the background.
3 - Is there a way to output the status of the test case to a web page and if the web page was closed, for the status to be availble if the web page was reopened?
Many thanks - oli
If you have a python function you can call from a Django django view maybe with a form as parameter input. If you have long running processes you might want to consider a tip from here: How to start a long-running process from a Django view?
from mytests import testfunc
def test_parameter_view(request):
if request.method == 'POST': # If the form has been submitted...
form = ParameterForm(request.POST)
if form.is_valid():
testfunc(form.cleaned_data['parameter']) # <-- Here the actual testing happens
return HttpResponseRedirect(reverse(test_result)) # Redirect after POST
else:
form = ParameterForm()
return render_to_response('test.html', {
'form': form,
})
In your test_result view you can access the test result values from the database.
If the user closes the browser or not doesn't affect server processes that already have been started. And since you write your results to the database they are persistent and can be accessed any time after the test has finished.
If you don't want to port over your scripts into django views, there is another way:
1 - Set up a form with all the options that you want passed to the script
2 - GET or POST the form params and save them to variables using var1 = request.POST['param1'], etc
3 - Use a module called subprocess to execute your script. http://docs.python.org/library/subprocess.html

Categories