Using a Bottle Sehttp://bottlepy.org/docs/dev/routing.html#wildcard-filters
I'd like to accept any url, and then do something with the url.
e.g.
#bottle.route("/<url:path>")
def index(url):
return "Your url is " + url
This is tricky because URLs have slashes in them, and Bottle splits by slashes.
Based on new Bottle (v0.10), use a re filter:
#bottle.route("/<url:re:.+>")
You can do that with old parameters too:
#bottle.route("/:url#.+#")
I think you (OP) were on the right track to begin with. <mypath:path> should do the trick.
I just tried it out with bottle 0.10 and it works:
~>python test.py >& /dev/null &
[1] 37316
~>wget -qO- 'http://127.0.0.1:8090/hello/cruel/world'
Your path is: /hello/cruel/world
Here's my code. What happens when you run this on your system?
from bottle import route, run
#route('<mypath:path>')
def test(mypath):
return 'Your path is: %s\n' % mypath
run(host='localhost', port=8090)
Cheers!
In Bottle 0.12.9 i did this to achieve optional dynamic routes:
#bottle.route("/<url:re:.*>")
def index(url):
return "Your url is " + url
#bottle.route("/hello/:myurl")
def something(myurl):
print myurl
return "Your url was %s" % myurl
Should work just fine
I would then write the regex into the function itself.
Or you could do it with a new filter, but to do that you have to write a filter function and add it to the app.
Related
I have my api built with this pattern: api.hostname/endpoint.
However there is a plugin to my app that uses hostname/endpoint pattern.
I would like to solve it on the backend side by adding redirection to api.hostname/endpoint.
I tried to experiment with adding urls or paths to urlpatterns, but it didn't help me.
How can I achieve it? Any ideas?
Regards,
Maciej.
You can use urllib
import urllib.parse
url = "https://hostname/endpoint"
split_url = urllib.parse.urlsplit(url)
result = f"{split_url.scheme}://api.{split_url.hostname}/{split_url.endpoint}"
print(result)
>> "https://api.hostname/endpoint"
Facing some constraints in a website, I was obligated to try to post data to some view from another view (I suppose it does make sense), like:
def view1(request):
if request.method == 'POST':
value = request.POST.get('h1')
''' '''
And in my view2, I would do something like:
def view2(request):
if constraint:
python.post(/url/view1/,data={'h1':1}) # Doesn't exist
# Just a demonstration
Is there a way to do what I want?
you could use the requests package to send request to other URLs, the question is "why" ??.
Why not extract the code of view1 in a utility function and call int from view2?
If you need to use an new HTTP request, I suggest to use the Django reverse() function to the the URL from the urls.py configuration (refer to the official documentation )
Use the requests library to do this.
Take a look at Python Requests: I found it in in Python forum to print which could be modified to post.
import requests
req = requests.Request('POST','http://stackoverflow.com',headers={'X-Custom':'Test'},data='a=1&b=2')
prepared = req.prepare()
def pretty_print_POST(req):
"""
At this point it is completely built and ready
to be fired; it is "prepared".
However pay attention at the formatting used in
this function because it is programmed to be pretty
printed and may differ from the actual request.
"""
print('{}\n{}\n{}\n\n{}'.format(
'-----------START-----------',
req.method + ' ' + req.url,
'\n'.join('{}: {}'.format(k, v) for k, v in req.headers.items()),
req.body,
))
pretty_print_POST(prepared)
I initially gave URLs like #app.route('/volume/') and #app.route('/cvolume/') where c denoted another section. But now I think section/page would be better than c prefix to the page i.e. #app.route('/c/volume/'). Can I simply make the change or will this break my app?
P.S. - I am using <a href="{{url_for("volume")}}> in templates instead of the plain <a href="/volume">
No, because url_for takes the name of the function, not the url. So if your function is:
# ...Code, imports...
#app.route('/cvolume/')
def volume():
return 'Hello world!'
#app.route('/volume/')
def volume_2():
return 'Hello You!'
#app.route('/test/')
def test():
return redirect(url_for('volume'))
The redirection would be for /cvolume/ not /volume/.
Current url is
http://myapp.appspot.com/something/<user-id>
or
http://127.0.0.1:8080/something/<user-id>
How in my python code I can get http://myapp.appspot.com/ or http://127.0.0.1:8080/?
This is need for dynamic links generation, for ex., to http://myapp.appspot.com/somethingelse.
self.request.path returns the whole path.
self.request.host_url
I think you want app_identity.get_default_version_hostname().
If an app is served from a custom domain, it may be necessary to
retrieve the entire hostname component. You can do this using the
app_identity.get_default_version_hostname() method.
This code:
logging.info(app_identity.get_default_version_hostname())
prints localhost:8080 on the development server.
If self.request.path returns the whole path, can't you just do:
import urlparse
def get_domain(url):
return urlparse.urlparse(url).netloc
>>> get_domain("http://myapp.appspot.com/something/")
'myapp.appspot.com'
Looking for a python script that would simply connect to a web page (maybe some querystring parameters).
I am going to run this script as a batch job in unix.
urllib2 will do what you want and it's pretty simple to use.
import urllib
import urllib2
params = {'param1': 'value1'}
req = urllib2.Request("http://someurl", urllib.urlencode(params))
res = urllib2.urlopen(req)
data = res.read()
It's also nice because it's easy to modify the above code to do all sorts of other things like POST requests, Basic Authentication, etc.
Try this:
aResp = urllib2.urlopen("http://google.com/");
print aResp.read();
If you need your script to actually function as a user of the site (clicking links, etc.) then you're probably looking for the python mechanize library.
Python Mechanize
A simple wget called from a shell script might suffice.
in python 2.7:
import urllib2
params = "key=val&key2=val2" #make sure that it's in GET request format
url = "http://www.example.com"
html = urllib2.urlopen(url+"?"+params).read()
print html
more info at https://docs.python.org/2.7/library/urllib2.html
in python 3.6:
from urllib.request import urlopen
params = "key=val&key2=val2" #make sure that it's in GET request format
url = "http://www.example.com"
html = urlopen(url+"?"+params).read()
print(html)
more info at https://docs.python.org/3.6/library/urllib.request.html
to encode params into GET format:
def myEncode(dictionary):
result = ""
for k in dictionary: #k is the key
result += k+"="+dictionary[k]+"&"
return result[:-1] #all but that last `&`
I'm pretty sure this should work in either python2 or python3...
What are you trying to do? If you're just trying to fetch a web page, cURL is a pre-existing (and very common) tool that does exactly that.
Basic usage is very simple:
curl www.example.com
You might want to simply use httplib from the standard library.
myConnection = httplib.HTTPConnection('http://www.example.com')
you can find the official reference here: http://docs.python.org/library/httplib.html