pyramid: get application absolute url - python

Is there any way to get pyramid absolute application url in main() function?
I want to add it into global settings, so it could be called every where(in templates and js files).
In pyramid documents there is some functions would help, but all of them need a request object and must call in a view.
Thanks.

Pyramid (like most WSGI applications) can be mounted on any domain and url prefix. Thus the application itself doesn't actually know what urls it is responsible for unless you code that into your application specifically (an INI setting, for example).
This is why request.application_url exists... because the application_url could be different per request based on how many different domains and url prefixes you have that are proxying requests to your application.

I just get the full route for my index route, 'home' in my case:
I set this in my main wrapper mako template so that all of my JS calls can reference it to build a proper path for ajax calls/etc
<script type="text/javascript" charset="utf-8">
<%
app_url = request.route_url('home').rstrip('/')
%>
APP_URL = '${app_url}';
</script>

Related

Automatic page refresh stops working (Flask App)

I created a Flask app that displays the latest pictures on an HTML website. The website is set to automatically refresh every 10 seconds using a meta tag
<meta http-equiv="refresh" content="10" />
it all works great when the server and website run on a local PC, but when I run the app over LAN, the page refreshes correctly a few times, but sooner or later it stops. The webpage itself looks like it is loading (spinning wheel), but no new requests are registered in the flask app. The only way to start refreshing it again is by manual refresh on the client-side or by restarting the flask app on the server-side.
What could be the problem that causes this and how to mitigate it? Can it be caused by a firewall that doesn't like the constant refreshes? Are there any alternatives to said meta tag? I don't want to have any difficult set-up on the client-side like job scheduling etc (unless it is the only solution).
You could just use javascript for this. Just put the code below in your html file somewhere or in a seperate javascript file named script.js and link that javascript file like <script src="/Path/To/File.js"></script>
<script>
window.setTimeout(function () {
window.location.reload();
}, 30000);
</script>

static_url_path and variable rules

Variable rules isn't working as I'd expect when static_url_path is used.
Simply, why does this work:
import flask
app = flask.Flask(__name__)
#app.route("/", defaults={"p": "")
#app.route("/<path:p>")
def main(p):
return "<h1>Hello %s</h1>" % p
if __name__ == '__main__':
app.run(debug=True)
But not this?
import flask
app = flask.Flask(__name__, static_url_path="")
#app.route("/", defaults={"p": "")
#app.route("/<path:p>")
def main(p):
return "<h1>Hello %s</h1>" % p
if __name__ == '__main__':
app.run(debug=True)
Note the added static_url_path
Some background details; I'm new to both Flask and AngularJS, but are using them here in conjunction with each other and for those not familiar with AngularJS; I'm using AngularJS to produce a single-page application in which paths are used for dynamically replacing content within a document, as opposed to reloading the whole page. Thus, I need all paths routed to the same html document (not included in the above example), ideally coming form the same function, so as to let AngularJS handle rendering as opposed to Flask.
The below answer solved that issue, but it isn't working when status_url_path is used, and I can't figure out why.
Flask route for AngularJS with HTML5 URL mode
Adding this for reference, as he is doing this exact thing.
http://www.youtube.com/watch?v=2geC50roans
You are effectively telling Flask to map /<path:static_path> to static files. That means that everything is now considered static. Don't do this!
Angular pages don't need to call into Flask static routes; keep your static routes under /static, have / produce your Angular application, then use other routes to handle Angular AJAX calls. These can have proper paths; Angular doesn't dictate what routes your Flask server will respond to.
Then keep your static route to serve the JavaScript and CSS and images, e.g. the actual static content referenced from your HTML page.

Django-s3direct upload image

I want use django-s3direct and I want upload many image in admin panel.
1) All time when I try upload image/file get error "Oops, file upload failed, please try again" ?
When I refresh page. Name file is in input. But my input "Save" are disabled :/
edit
I remove from settings:
AWS_SECRET_ACCESS_KEY = ''
AWS_ACCESS_KEY_ID = ''
AWS_STORAGE_BUCKET_NAME = ''
and now I don't get error but file no upload :/ All time black progress bar..
2) How upload multiple image? No inline.. Please help me and give some advice? Im newbie..
I have Django 1.5.5. Now i use inline and I don't know what's next.
You will need to edit some of the permissions properties of the target S3 bucket so that the final request has sufficient privileges to write to the bucket. Sign in to the AWS console and select the S3 section. Select the appropriate bucket and click the ‘Properties’ tab. Select the Permissions section and three options are provided (Add more permissions, Edit bucket policy and Edit CORS configuration).
CORS (Cross-Origin Resource Sharing) will allow your application to access content in the S3 bucket. Each rule should specify a set of domains from which access to the bucket is granted and also the methods and headers permitted from those domains.
For this to work in your application, click ‘Add CORS Configuration’ and enter the following XML:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>yourdomain.com</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
Click ‘Save’ in the CORS window and then ‘Save’ again in the bucket’s ‘Properties’ tab.
This tells S3 to allow any domain access to the bucket and that requests can contain any headers. For security, you can change the ‘AllowedOrigin’ to only accept requests from your domain.
If you wish to use S3 credentials specifically for this application, then more keys can be generated in the AWS account pages. This provides further security, since you can designate a very specific set of requests that this set of keys are able to perform. If this is preferable to you, then you will need to also set up an IAM user in the Edit bucket policy option in your S3 bucket. There are various guides on AWS’s web pages detailing how this can be accomplished.
Setting up the client-side code
This setup does not require any additional, non-standard Python libraries, but some scripts are necessary to complete the implementation on the client-side.
This article covers the use of the s3upload.js script. Obtain this script from the project’s repo (using Git or otherwise) and store it somewhere appropriate in your application’s static directory. This script currently depends on both the JQuery and Lo-Dash libraries. Inclusion of these in your application will be covered later on in this guide.
The HTML and JavaScript can now be created to handle the file selection, obtain the request and signature from your Python application, and then finally make the upload request.
Firstly, create a file called account.html in your application’s templates directory and populate the head and other necessary HTML tags appropriately for your application. In the body of this HTML file, include a file input and an element that will contain status updates on the upload progress.
<input type="file" id="file" onchange="s3_upload();"/>
<p id="status">Please select a file</p>
<div id="preview"><img src="/static/default.png" /></div>
<form method="POST" action="/submit_form/">
<input type="hidden" id="" name="" value="/static/default.png" />
<input type="text" name="example" placeholder="" /><br />
<input type="text" name="example2" placeholder="" /><br /><br />
<input type="submit" value="" />
</form>
The preview element initially holds a default image. Both of these are updated by the JavaScript, discussed below, when the user selects a new image.
Thus when the user finally clicks the submit button, the URL of the image is submitted, along with the other details of the user, to your desired endpoint for server-side handling. The JavaScript method, s3_upload(), is called when a file is selected by the user. The creation and population of this method is covered below.
Next, include the three dependency scripts in your HTML file,account.html. You may need to adjust the src attribute for the files3upload.js if you put this file in a directory other than /static:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="https://raw.github.com/bestiejs/lodash/v1.1.1/dist/lodash.min.js"></script>
<script type="text/javascript" src="/static/s3upload.js"></script>
The ordering of the scripts is important as the dependencies need to be satisfied in this sequence. If you desire to host your own versions of JQuery and Lo-Dash, then adjust thesrc attribute accordingly.
Finally, in a block, declare a JavaScript function,s3_upload(), in the same file again to process the file upload. This block will need to exist below the inclusion of the three dependencies:
function s3_upload(){
var s3upload = new S3Upload({
file_dom_selector: 'file',
s3_sign_put_url: '/sign_s3_upload/',
onProgress: function(percent, message) {
$('#status').html('Upload progress: ' + percent + '%' + message);
},
onFinishS3Put: function(url) {
$('#status').html('Upload completed. Uploaded to: '+ url);
$("#image_url").val(url);
$("#preview").html('<img src="'+url+'" style="width:300px;" />');
},
onError: function(status) {
$('#status').html('Upload error: ' + status);
}
});
}
This function creates a new instance of S3Upload, to which is passed the file input element, the URL from which to retrieve the signed request and three functions.
Initially, the function makes a request to the URL denoted by thes3_sign_put_url argument, passing the file name and mime type as GET parameters. The server-side code (covered in the next section) interprets the request and responds with a preview of the URL of the file to be uploaded to S3 and the signed request, which this function then uses to asynchronously upload the file to your bucket.
The function will post upload updates to the onProgress() function and , if the upload is successful, onFinishS3Put() is called and the URL returned by the Python application view is received as an argument. If, for any reason, the upload should fail, onError() will be called and thestatus parameter will describe the error.
If you find that the page isn’t working as you intend after implementing the system, then consider using console.log()to record any errors that occur inside the onError() callback and use your browser’s error console to help diagnose the problem.
If successful, the preview div will now be updated with the user’s chosen image, and the hidden input field will contain the URL for the image. Now, once the user has completed the rest of the form and clicked submit, all pieces of information can be posted to the same endpoint.
It is good practice to inform the user of any prolonged activity in any form of application (web- or device-based) and to display updates on changes. Thus the status methods could be used, for example, to show a loading GIF to indicate that an upload is in progress, which can then be hidden when the upload has finished. Without this sort of information, users may suspect that the page has crashed, and could try to refresh the page or otherwise disrupt the upload process.
Setting up the server-side Python code
To generate a temporary signature with which the upload request can be signed. This temporary signature uses the account details (the AWS access key and secret access key) as a basis for the signature, but users will not have direct access to this information. After the signature has expired, then upload requests with the same signature will not be successful.
As mentioned previously, this article covers the production of an application for the Flask framework, although the steps for other Python frameworks will be similar. Readers using Python 3 should consider therelevant information on Flask’s website before continuing.
Start by creating your main application file, application.py, and set up your skeleton application appropriately:
from flask import Flask, render_template, request
from hashlib import sha1
import time, os, json, base64, hmac, urllib
app = Flask(__name__)
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
The currently-unused import statements will be necessary later on.
Readers using Python 3 should import urllib.parse in place of urllib.
Next, in the same file, you will need to create the views responsible for returning the correct information back to the user’s browser when requests are made to various URLs. First define view for requests to/account to return the page account.html, which contains the form for the user to complete:
#app.route("/account/")
def account():
return render_template('account.html')
Please note that the views for the application will need to be placed between the app = Flask(__name__) and if __name__ == '__main__': lines in application.py.
Now create the view, in the same Python file, that is responsible for generating and returning the signature with which the client-side JavaScript can upload the image. This is the first request made by the client before attempting an upload to S3. This view responds with requests to /sign_s3/:
#app.route('/sign_s3/')
def sign_s3():
AWS_ACCESS_KEY = os.environ.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
S3_BUCKET = os.environ.get('S3_BUCKET')
object_name = request.args.get('s3_object_name')
mime_type = request.args.get('s3_object_type')
expires = int(time.time()+10)
amz_headers = "x-amz-acl:public-read"
put_request = "PUT\n\n%s\n%d\n%s\n/%s/%s" % (mime_type, expires, amz_headers, S3_BUCKET, object_name)
signature = base64.encodestring(hmac.new(AWS_SECRET_KEY, put_request, sha1).digest())
signature = urllib.quote_plus(signature.strip())
url = 'https://%s.s3.amazonaws.com/%s' % (S3_BUCKET, object_name)
return json.dumps({
'signed_request': '%s?AWSAccessKeyId=%s&Expires=%d&Signature=%s' % (url, AWS_ACCESS_KEY, expires, signature),
'url': url
})
Readers using Python 3 should useurllib.parse.quote_plus() to quote the signature.
This code performs the following steps:
• The request is received to /sign_s3/ and the AWS keys and S3 bucket name are loaded from the environment.
• The name and mime type of the object to be uploaded are extracted from the GET parameters of the request (this stage may differ in other frameworks).
• The expiry time of the signature is set and forms the basis of the temporary nature of the signature. As shown, this is best used as a function relative to the current UNIX time. In this example, the signature will expire 10 seconds after Python has executed that line of code.
• The headers line tells S3 what access permissions to grant. In this case, the object will be publicly available for download.
• Now the PUT request can be constructed from the object information, headers and expiry time.
• The signature is generated as an SHA hash of the compiled AWS secret key and the actual PUT request.
• In addition, surrounding whitespace is stripped from the signature and special characters are escaped (using quote_plus) for safer transmission through HTTP.
• The prospective URL of the object to be uploaded is produced as a combination of the S3 bucket name and the object name.
• Finally, the signed request can be returned, along with the prospective URL, to the browser in JSON format.
You may wish to assign another, customised name to the object instead of using the one that the file is already named with, which is useful for preventing accidental overwrites in the S3 bucket. This name could be related to the ID of the user’s account, for example. If not, you should provide some method for properly quoting the name in case there are spaces or other awkward characters present. In addition, this is the stage at which you could provide checks on the uploaded file in order to restrict access to certain file types. For example, a simple check could be implemented to allow only .png files to proceed beyond this point.
It is sometimes possible for S3 to respond with 403 (forbidden) errors for requests which are signed by temporary signatures containing special characters. Therefore, it is important to appropriately quote the signature as demonstrated above.
Finally, in application.py, create the view responsible for receiving the account information after the user has uploaded an image, filled in the form, and clicked submit. Since this will be a POST request, this will also need to be defined as an ‘allowed access method’. This method will respond to requests to the URL /submit_form/:
#app.route("/submit_form/", methods=["POST"])
def submit_form():
example = request.form[""]
example2 = request.form[""]
image_url = request.form["image_url"]
update_account(example, example2, image_url)
return redirect(url_for('profile'))
In this example, an update_account() function has been called, but creation of this method is not covered in this article. In your application, you should provide some functionality, at this stage, to allow the app to store these account details in some form of database and correctly associate the information with the rest of the user’s account details.
In addition, the URL for the profile page has not been defined in this article (or companion code). Ideally, for example, after updating the account, the user would be redirected back to their own profile so that they can see the updated information.
For more information http://www.tivix.com/blog/easy-user-uploads-with-direct-s3-uploading/

How to remove used endpoints when running flask application using virtual env

I have a view python file which has the code:
#app.route('/')
def index():
page = """
<html>
<head>
</head>
.....
...
</html>
I made some changes to this file , those just normal changes like importing render_template.I was able to see the html file using foreman start command in my localhost. However after some changes as I mentioned earlier , when I again start using foreman start I get an error - " View function mapping is overwriting an existing endpoint function: index "
However when I used #app.route('/',endpoint ="new"), it worked.
Looks like it reserving some endpoints and not letting me override it. How can I remove all the endpoints to start fresh.
Make sure you don't have two routes with the same URI.

Twisted Web behind Apache - How to correct links?

I am attempting to write a web application using the Twisted framework for python.
I want the application to work if run as a standalone server (ala twistd), or if Apache reverse proxies to it. E.g.
Apache https://example.com/twisted/ --> https://internal.example.com/
After doing some research, it seemed like I needed to use the vhost.VHostMonsterResource to make this work. So I set up apache with the following directive:
ProxyPass /twisted https://localhost:8090/twisted/https/127.0.0.1:443
Here is my basic SSL server:
from twisted.web import server, resource, static
from twisted.internet import reactor
from twisted.application import service, internet
from twisted.internet.ssl import SSL
from twisted.web import vhost
import sys
import os.path
from textwrap import dedent
PORT = 8090
KEY_PATH = "/home/waldbiec/projects/python/twisted"
PATH = "/home/waldbiec/projects/python/twisted/static_files"
class Index(resource.Resource):
def render_GET(self, request):
html = dedent("""\
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Index</title>
</head>
<body>
<h1>Index</h1>
<ul>
<li>Files</li>
</ul>
</body>
</html>
""")
return html
class ServerContextFactory:
def getContext(self):
"""
Create an SSL context.
Similar to twisted's echoserv_ssl example, except the private key
and certificate are in separate files.
"""
ctx = SSL.Context(SSL.SSLv23_METHOD)
ctx.use_privatekey_file(os.path.join(KEY_PATH, 'serverkey.pem'))
ctx.use_certificate_file(os.path.join(KEY_PATH, 'servercert.pem'))
return ctx
class SSLService(internet.SSLServer):
def __init__(self):
root = resource.Resource()
root.putChild("", Index())
root.putChild("twisted", vhost.VHostMonsterResource())
root.putChild("files", static.File(PATH))
site = server.Site(root)
internet.SSLServer.__init__(self, PORT, site, ServerContextFactory())
application = service.Application("SSLServer")
ssl_service = SSLService()
ssl_service.setServiceParent(application)
It almost works-- but the "files" link on the index page does not behave how I want it to when using apache as a reverse proxy, because it is an absolute link.
My main question is, other than using a relative link, is there some way to compute what the full URL path of the link ought to be in such a way that the link still works in standalone server mode?
A second question would be, am I using VHostMonsterResource correctly? I did not find much documentation, and I pieced together my code from examples I found on the web.
This seems like too much work. Why use VHostMonsterResource at all? You may have very specific reasons for wanting some of this but....Most times:
Have apache handle the ssl. apache then passes off to your twisted app serving non SSL goodies back to apache. Documentation all over the net on the apache config stuff.
you can sill add another server on an ssl port if you really want to
Haven't tested but structure more like:
root = resource.Resource()
root.putChild("", Index())
root.putChild("files", static.File(PATH))
http = internet.TCPServer(8090, server.Site(root))
# change this port # to 443 if no apache
https= internet.SSLServer(8443, server.Site(root), ServerContextFactory())
application = service.Application("http_https_Server")
http.setServiceParent(application)
https.setServiceParent(application)
Dev tip:
During development, for the cost of a couple of extra lines you can add an ssl server so that you can ssh into the running web_server and inspect variables and other state. Way cool.
ssl = internet.TCPServer(8022, getManholeFactory(globals(), waldbiec ='some non-system waldbiec passwork'))
ssl.setServiceParent(application)
Configure the Twisted application so that it knows its own root location. It can use that information to generate URLs correctly.
So after digging into the vhost.VHostMonsterResource source, I determined I could create another resource that could let the reverse proxied URL prefix be specified by an additional marker in the Apache ProxyPass URL.
Firstly, I finally figured out that vhost.VHostMonsterResource is supposed to be a special URL in your back end web site that figures out the reverse proxy host and port from data encoded in the URL path. The URL path (sans scheme and net location) looks like:
/$PATH_TO_VHMONST_RES/$REV_PROXY_SCHEME/$REV_PROXY_NETLOC/real/url/components/
$PATH_TO_VHMONST : Path in the (internal) twisted site that corresponds to the VHostMonsterResource resource.
$REV_PROXY_SCHEME : http or https that is being used by the reverse proxy (Apache).
$REV_PROXY_NETLOC : The net location (host and port) or the reverse proxy (Apache).
So you can control the configuration from the reverse proxy by encoding this information in the URL. The result is that the twisted site will understand the HTTP request came from the reverse proxy.
However, if you are proxying a subtree of the external site as per my original example, this information is lost. So my solution was to create an additional resource that can decode the extra path information. The new proxy URL path becomes:
/$PATH_TO_MANGLE_RES/$REV_PROXY_PATH_PREFIX/$VHOSTMONST_MARKER/$REV_PROXY_SCHEME/$REV_PROXY_NETLOC/real/url/components/
$PATH_TO_MANGLE_RES : The path to the resource that decodes the reverse proxy path info.
$REV_PROXY_PATH_PREFIX : The subtree prefix of the reverse proxy.
$VHOSTMONST_MARKER : A path component (e.g. "vhost") that signals a VHostMonster Resource should be used to further decode the path.

Categories

Resources