I am trying to set up Google App Engine unit testing for my web application. I downloaded the file from here.
I followed the instructions in the readmen by copying the directory gaeunit into the directory with the rest of my apps and registering 'gaeunit' in settings.py. This didn't seem sufficient to actually get things going. I also stuck url('^test(.*)', include('gaeunit.urls')) into my urls.py file.
When I go to the url http://localhost:8000/test, I get the following error:
[Errno 2] No such file or directory: '../../gaeunit/test'
Any suggestions? I'm not sure what I've done wrong. Thanks!
You can copy url but in your urls.py include
(r'^test', include('gaeunit.urls')),
Also you will have to change test path in gaeunit.py
_LOCAL_DJANGO_TEST_DIR = 'test'
And in your main web test files under test folder include following line for django test setup
self.application = django.core.handlers.wsgi.WSGIHandler()
According to the instructions on the main page you should add the URL to app.yaml, not urls.py.
- url: /test.*
script: gaeunit.py
Related
Here is a simple static FastAPI app. With this setup even though the root path is expected to return a FileResponse of custom.html, the app still returns index.html. How can I get the root path work and render custom.html?
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
app = FastAPI()
app.mount(
"/",
StaticFiles(directory="static", html=True),
name="static",
)
#app.get("/")
async def index() -> FileResponse:
return FileResponse("custom.html", media_type="html")
As per Starlette documentation:
StaticFiles
Signature: StaticFiles(directory=None, packages=None, check_dir=True)
html - Run in HTML mode. Automatically loads index.html for directories if such file exists.
In addtion, as shown from the code snippet you provided, you have mounted StaticFiles to the root directory (i.e., '/'), instead of, for example, /static (or some other path name), as shown below:
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
app = FastAPI()
app.mount('/static', StaticFiles(directory='static'), name='static')
As per FastAPI documentation:
"Mounting" means adding a complete "independent" application in a
specific path, that then takes care of handling all the sub-paths.
Hence, any path that starts with '/' will be handled by that StaticFiles application, and due to specifying html=True in the arguments, index.html will be automatically loaded; regardless of creating a separate endpoint pointing to the root path / and trying to return something else, as demonstrated in the example given in your question.
Important
If, for example, you moved app.mount("/",StaticFiles(... line after defining your #app.get("/") endpoint, you would see that order matters and index.html would not be automatically loaded anymore, as endpoints are evaluated in order. Note that, in your case, you might get an Internal Server Error, as your #app.get("/") endpoint would be called and attempt to find custom.html, but if this file exists under 'static' directory (as shown from your code) and not under '/', you would then get a File does not exist error, and you should instead return FileResponse('static/custom.html').
Even if you removed html=True, but keep StaticFiles mounted to the root directory (and defined before your '/' endpoint), you would get a {"detail":"Not Found"} error response when attempting to access http://localhost:8000/. This is because that request is still handled by that application (as mentioned earlier) and you should now need to specify the file that you would like to access, e.g., http://localhost:8000/index.html. Even if you defined other endpoints in your code (e.g., /register, /login, /hello)—as long as StaticFiles is mounted to the root directory (i.e., '/') and defined in your code before all other endpoints—all requests to those routes would be handled by StaticFiles application and lead to a {"detail":"Not Found"} error response.
The html=True simply provides an easy way to serve a directory of web content with just one line of code. If you only need to serve static files, such as package docs directory, then this is the way to go. If, however, you need to serve different HTML files that will get dynamically updated, as well as you wish to create additional routes/endpoints, you should have a look at Templates (not FileResponse), as well as mount your StaticFiles to a different directory (e.g., /static), rather than root directory (and without using html=True).
I am working on a website. For this website I have to create a table which shows the time of the meeting and the participants of it. I am writing the code of site using Django. For the table I have a data on a .json file. When I run the server locally it works fine and when I push it to heroku it raises FileNotFoundError. I found this question which faces with the similar problem but the answer shows how to log something, but I need .json file for data. My django app directory:
66 admin.py
100 apps.py
<DIR> migrations
60 models.py
3,332 schedule_of_teams.json
<DIR> static
<DIR> templates
63 tests.py
333 urls.py
807 views.py
So I have a view function in views.py file:
def schedule_of_teams(request):
with open('./schedule_of_teams.json',encoding='utf-8') as f:
context = json.load(f)
context['title'] = 'Yarış cədvəli'
return render(request,'schedule_of_teams.html',context)
And open context manager raises the error:
FileNotFoundError at /schedule_of_teams/
[Errno 2] No such file or directory './schedule_of_teams.json/'
So why is this happening? Why it works fine when I run python manage.py runserver with localhost but when I push to heroku it raises this exception? Is heroku ignores .json files? By the way, I do not have *.json on my .gitignore file it commits the file.
What I have tried:
I tried to change the directory of the file like moving it to a folder data/ or firstly instead of open('./schedule_of_teams.json) I wrote open('schedule_of_teams.json') but that didn't work either.
I am literally so confused I asked this question in Python Discord Server but got no respond. One of the solutions is creating a database but I do not want to do it, since this data is just a list which has 16 dictionaries and each has 4 keys.
I'm a real newbie to Django, (following tutorial in openclassroom)
I have a django project called "blog", the code in the file "urls.py" of the main DjangoProject is this:
DjangoProject\urls.py
The code in blog\urls is this:
blog\urls.py
When I run the server, I get this:
Result
Help is very much appreciated !
on your project urls.py you should change this path('blog/') to this path('') as in your case you do not have configured the path ('/') on your project urls so the / is not found because the blog is linked to localhost:8000/blog url
The problem lies in your URL configurations. You are navigating to https://127.0.0.1:8000/, but this is not a URL you have defined. Your available URL paths are https://127.0.0.1:8000/admin/ and https://127.0.0.1:8000/blog/. Navigate to https://127.0.0.1:8000/blog/ and it should be working.
Or make the following change to your DjangoProject/urls.py:
path('', include ('blog.urls'))
Hope this helps.
I am using Django 1.6.2 in virtualenv, Ubuntu 12.04 LTS. As I wanted to shift my project to https, I installed django-sslserver. The project needs self signing, and works fine for Home Page. However, apps in my django project encounter problems. Not all pages are redirected to https, and hence causes 404 error (works only if explicitly prefixed as https). Also, the overall template (appearance i.e. static files?) is lost.
What exactly is happening here? How to make sure that all pages are redirected to https and works the same way as in http?
Edited: My pull request has been merged. Static resources are served normally now.
The problem is that the runsslserver command is not implemented to serve static resources. A way to fix is to override get_handler in PATH_TO_PYTHON_SITE_PACKAGE/sslserver/management/commands/runsslserver.py like so:
# ...
from django.contrib.staticfiles.handlers import StaticFilesHandler
from django import get_version
# ...
class Command(runserver.Command):
# ...
help = "Run a Django development server over HTTPS"
def get_handler(self, *args, **options):
"""
Returns the static files serving handler wrapping the default handler,
if static files should be served. Otherwise just returns the default
handler.
"""
handler = super(Command, self).get_handler(*args, **options)
use_static_handler = options.get('use_static_handler', True)
insecure_serving = options.get('insecure_serving', False)
if use_static_handler:
return StaticFilesHandler(handler)
return handler
# ...
You might want to get your site package path with
python -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())"
I've also submitted a pull request in case you want to branch, merge, and reinstall it as a package on your own.
Cheers
So I have successfully deployed an app using webapp2/jinja2 and a Paste server, but am having trouble serving static stylesheets.
I have had luck accessing static files via this method, as well as implementing a StaticFileHandler I found with some google-fu:
import os
import mimetypes
import webapp2
import logging
class StaticFileHandler(webapp2.RequestHandler):
def get(self, path):
abs_path = os.path.abspath(os.path.join(self.app.config.get('webapp2_static.static_file_path', 'static'), path))
if os.path.isdir(abs_path) or abs_path.find(os.getcwd()) != 0:
self.response.set_status(403)
return
try:
f = open(abs_path, 'r')
self.response.headers.add_header('Content-Type', mimetypes.guess_type(abs_path)[0])
self.response.out.write(f.read())
f.close()
except:
self.response.set_status(404)
where my main app routing looks like:
app = webapp2.WSGIApplication([('/', HelloWorld),
(r'/display', DisplayHandler),
(r'/static/(.+)', StaticFileHandler)
], debug=True)
My css files are in a folder under the app root: /static/css/main.css
I can access the file via direct url, and even link it as a stylesheet, but the styles won't apply. Any ideas? Is there another way to serve stylesheets? Some way to implement an app.yaml similar to GAE?
you dont need a static file handler.
upload the app with the static file folder by adding this to your app.yaml
- url: /static/
static_dir: static
docs are here: https://developers.google.com/appengine/docs/python/config/appconfig#Static_Directory_Handlers
edit:
see answer below in comments
#Mnemon, hats off to you for solving my problem. I would upvote you but I'm not allowed to do that. You convinced me that if it's not the only webapp2 way without GAE, it's at least a way that will work.
But also I can contribute that your solution is now installable as "pip install webapp2_static", from pipi--- by an author who seems to be using his real name... you I'm sure. Other webapp2 docs that I found helpful are available here.
I'm implementing your code on a Linux desktop development server, using paste, which you also used:
def main():
from paste import httpserver
httpserver.serve(app, host='127.0.0.1', port='8080')
But with the code as you have it above (which appears to be utterly identical to that of webapp2_static.py file), I don't find that putting my css files in a folder named static in the app root works as you said.
For example, I have /home/user/proj/public_html/app/app.py, where the py file contains your code plus other "views" for my ultra-simple site. (I don't know how paste really works, so maybe for now the public_html is just in there for reference so that I don't become confused when I'm uploading stuff onto the production server.)
So if I put the css stylesheets into a folder named /static, then, if I put /static in as either a subdirectory of /app or of /public_html I find that neither location works; I must instead make it a subdirectory of /proj.
I wasn't expecting that, but the cure for me is to change the default 'static' in your app.configure.get(..., 'static') call, to 'public_html/app/static'. Then it works, with the /static folder inside /app.
Similarly using the pipi code with './app/static/ in place of the default 'static' doesn't work; I found that I need ./public_html/app/static instead (or maybe it was just /public_html/app/static or even public_html/app/static... I forgot... one of those worked).
I tested how your computation of abs_path works and have reworked it in the code below, in which I have junked your approach in favor of something more Djangoesque. To wit, in my one app py file I put at the top the following:
STATIC_DIR = os.sep + 'tostatic' + os.path.abspath(os.path.dirname(__file__)) + os.sep + 'static'
Then in the page to which I want to add css, my Home page in my case, I put a very readable:
<link href="{{STATIC_DIR}}/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css">
For the "view" that generates my Home page I have (env is a jinja2 Environment object that takes a template loader as an argument):
class Home(webapp2.RequestHandler):
def get(self):
template = env.get_template('index.html')
template_values = {'STATIC_DIR': STATIC_DIR }
self.response.write(template.render(template_values))
And finally the URL routing is as in:
app = webapp2.WSGIApplication(
[
(r'/', Home),
(r'/tostatic/(.+)', StaticView),
], debug=True)
The view for the static file serving is now:
class StaticView(webapp2.RequestHandler):
def get(self, path):
path = os.sep + path
try:
f = open(path, 'r')
self.response.headers.add_header('Content-Type', mimetypes.guess_type(path)[0])
self.response.out.write(f.read())
f.close()
except Exception, e:
print 'Problem in StaticView:', e
self.response.set_status(404)
To finally close, the problem that I had with your approach is the one that I and other near noobs have with the departure of URLs from the legacy association with the file system. In your approach "static" is both a sub-directory and a string between slashes at the front of the URL that tells the interpreter which view (which webapp2.RequestHandler subclass) to run. You take the /static from the rest of the URL and then later hard-code it back on. And when it comes time to decide what to put in for href in the tag the HTML page coder has to remember that duplicity. With the {{STATIC_DIR}} template variable approach it's clear what to do. And it's easy to redefine the location of the static files--- only the STATIC_DIR declaration has to be changed.
I found that self.response.set_status(404) shows up in Firebug, but not Firefox. Evidently with webapp2 you must provide and serve your own HTTP status code pages.
self.response.headers.add_header('Content-Type', mimetypes.guess_type(abs_path)[0])
self.response.headers['Content-Type'] = mimetypes.guess_type(abs_path)[0]