Jupyter notebook API to get notebooks - python

I have my jupyter hub and single-user server running. I am using Jupyter notebook REST APIs to get all available notebooks. I am using http://127.0.0.1:8000/user/username/api/contents . With this I am able to see all available notebooks on mu UI.
However when I try to do the same from my python script I am getting 200 response code but unable to extract any content as its redirecting to login page where I need to enter username and password for my user. I also tried to pass these credentials through requests package. Something like this
import requests
api_url = 'http://127.0.0.1:8000/user/username/api/contents'
result = requests.get(api_url, auth=('username', 'password'))
print result
print result.json()
The outpus is:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Jupyter Hub</title>
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/hub/static/css/style.min.css?v=d96e0760e0c2b7356ce89635b646c350" type="text/css"/>
<script src="/hub/static/components/requirejs/require.js?v=6da8be361b9ee26c5e721e76c6d4afce" type="text/javascript" charset="utf-8"></script>
<script>
require.config({
urlArgs: "v=('20170907062813',)",
baseUrl: '/hub/static/js',
paths: {
components: '../components',
jquery: '../components/jquery/jquery.min',
bootstrap: '../components/bootstrap/js/bootstrap.min',
moment: "../components/moment/moment",
},
shim: {
bootstrap: {
deps: ["jquery"],
exports: "bootstrap"
},
}
});
</script>
<script type="text/javascript">
window.jhdata = {
base_url: "/hub/",
prefix: "/",
}
</script>
</head>
<body>
<noscript>
<div id='noscript'>
Jupyter Hub requires JavaScript.<br>
Please enable it to proceed.
</div>
</noscript>
<div id="header" class="navbar navbar-static-top">
<div class="container">
<span id="jupyterhub-logo" class="pull-left"><img src='/hub/logo' alt='JupyterHub' class='jpy-logo' title='Home'/></span>
</div>
</div>
<div id="login-main" class="container">
<form action="/hub/login?next=%2Fhub%2Fuser%2Fpnda%2Fapi%2Fcontents" method="post" role="form">
<div class="auth-form-header">
Sign in
</div>
<div class='auth-form-body'>
<p id='insecure-login-warning' class='hidden'>
Warning: JupyterHub seems to be served over an unsecured HTTP connection.
We strongly recommend enabling HTTPS for JupyterHub.
</p>
<label for="username_input">Username:</label>
<input
id="username_input"
type="username"
autocapitalize="off"
autocorrect="off"
class="form-control"
name="username"
val=""
tabindex="1"
autofocus="autofocus"
/>
<label for='password_input'>Password:</label>
<input
type="password"
class="form-control"
name="password"
id="password_input"
tabindex="2"
/>
<input
type="submit"
id="login_submit"
class='btn btn-jupyter'
value='Sign In'
tabindex="3"
/>
</div>
</form>
</div>
<div class="modal fade" id="error-dialog" tabindex="-1" role="dialog" aria-labelledby="error-label" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="error-label">Error</h4>
</div>
<div class="modal-body">
<div class="ajax-error">
The error
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" data-dismiss="modal" data-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
<script>
if (window.location.protocol === "http:") {
// unhide http warning
var warning = document.getElementById('insecure-login-warning');
warning.className = warning.className.replace(/\bhidden\b/, '');
}
</script>
</body>
</html>
Traceback (most recent call last):
File "test.py", line 31, in <module>
check_running()
File "test.py", line 28, in check_running
contents = r.json()
File "/usr/lib/python2.7/dist-packages/requests/models.py", line 740, in json
return json.loads(self.content.decode(encoding), **kwargs)
File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
I am fairly new to Jupyter. My I missing out on something. How else can I authenticate my user prior calling any API.
Saw this in jupyerhub documentation - Note that the API token authorizes JupyterHub REST API requests. The same token does not authorize access to the Jupyter Notebook REST API provided by notebook servers managed by JupyterHub. A different token is used to access the Jupyter Notebook API.
So this is the exactly what I am looking for. How can I create this different token so as to access jupyter notebook APIs thorugh hub.

Jupyter Notebooks require an access token (this should show when you start up jupyter notebook). In my case, something like this, then worked:
import requests
#Note that the url doesn't have a user or username attribute
api_url = 'http://127.0.0.1:8888/api/contents'
payload = {'token': 'xxxxxx'}
result = requests.get(api_url
#, auth=('username', 'password')
,params = payload)

Related

Having a connection issue with cx_oracle on a Flask app

Im trying to develop an app that gets a user input (an excel spreadsheet) and then upload that information to a database depending if the user pressed option A or option B.
The issue I´m having is that when I submit and upload something and try to then click the "go back" botton and try to upload someting else, the script gives me an error.
The backend is:
#app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
#Read the excel that was dragged
file = request.files['file']
#Identify the survey and project switchs
survey_switch = request.form.get("switch-1")
project_switch = request.form.get("switch-2")
#Convert the file dragged into a dataframe
df = pd.read_excel(file, skiprows=3, engine='openpyxl')
if survey_switch == 'Survey' and project_switch != 'Project':
session["survey_switch"] = survey_switch
session["project_switch"] = None
connection = utils.CreateConnection(file, df)
#Insert the Survey on the file dragged
utils.CreateSurvey(file, connection, df)
return redirect(url_for('messages'))
if project_switch == 'Project' and survey_switch != 'Survey':
session["survey_switch"] = None
session["project_switch"] = project_switch
connection = utils.CreateConnection(file, df)
#Insert the Project on the file dragged
utils.CreateProject(file, connection, df)
return redirect(url_for('messages'))
if survey_switch == 'Survey' and project_switch == 'Project':
session["survey_switch"] = survey_switch
session["project_switch"] = project_switch
connection = utils.CreateConnection(file, df)
#Insert the Survey and Project on the file dragged
utils.CreateSurvey(file, connection, df)
utils.CreateProject(file, connection, df)
return redirect(url_for('messages'))
return render_template('SIMMetadata_index.html')
#Make the messages template
#app.route('/UserInterface', methods=['GET', 'POST'])
def messages():
#Make the go back
if request.method == 'POST':
session["survey_switch"] = None
session["project_switch"] = None
return redirect(url_for('index'))
return render_template('UserInterfaceMessages.html')
The frontend are:
Index page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE11">
<title>SIM Metadata</title>
<link href="../static/css/em-unity-1.6.0.min.css" media="all" rel="stylesheet" />
<script type="text/javascript" src="../static/js/vendor/svg4everybody.min.js"></script><!-
- polyfill for SVG icons -->
</head>
<body>
<!-- Banner azul del head-->
<header class="em-c-header em-c-header--blue" role="banner">
<div class="em-l-container em-c-header__inner">
<div class="em-c-header__body">
<div class="em-c-header__title-container">
<h2 class="em-c-header__title"><a href="#" rel="home" class="em-c-header__title-
link">SIM Metadata</a></h2>
</div>
</div>
</header>
<!-- la caja de drag files con el padding respectivo-->
<div class="em-u-padding">
<!-- asignar distinta clase em-is-valid si el documento insertado es valido o em-has-error
si no es valido--->
<form action="/" method="POST" enctype="multipart/form-data" autocomplete="off">
<div class="em-c-field em-c-field--file-upload ">
<label for="file" class="em-c-field__label">KDM Spreadsheet</label>
<div class="em-c-field__body">
<svg class="em-c-icon em-c-icon--large em-c-field__block-icon">
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="../static/images/48/em-<body>
<!-- Banner azul del head-->
<header class="em-c-header em-c-header--blue" role="banner">
<div class="em-l-container em-c-header__inner">
<div class="em-c-header__body">
<div class="em-c-header__title-container">
<h2 class="em-c-header__title"><a href="#" rel="home" class="em-c-header__title-
link">SIM Metadata</a></h2>
</div>
</div>
</header>
<!-- la caja de drag files con el padding respectivo-->
<div class="em-u-padding">
<!-- asignar distinta clase em-is-valid si el documento insertado es valido o em-has-error
si no es valido--->
<form action="/" method="POST" enctype="multipart/form-data" autocomplete="off">
<div class="em-c-field em-c-field--file-upload ">
<label for="file" class="em-c-field__label">KDM Spreadsheet</label>
<div class="em-c-field__body">
<svg class="em-c-icon em-c-icon--large em-c-field__block-icon">
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="../static/images/48/em-
icons.svg#upload"></use>
</svg>
<input type="file" name="file" id="file" class="em-c-file-upload"
placeholder="Placeholder" enctype="multipart/form-data" />
<ul class="em-c-field__list em-js-field-list">
<li class="em-c-field__item">Drag file here</li>
<li class="em-c-field__item em-c-field__item--small">Or click to choose file</li>
</ul>
</div>
<div class="em-c-field__note">The extension of the spreadsheet must be .xls or .xslx</div>
</div>
<ul class="em-c-switch-list">
<li class="em-c-switch-list__item">
<div class="em-c-field">
<div class="em-c-field__body">
<div class="em-c-switch">
<label class="em-c-switch__label" for="switch-1">
<span class="em-c-switch__toggle"></span>
<span class="em-c-switch__label-name">Upload Survey</span>
</label>
<input id="switch-1" type="checkbox" name="switch-1" value="Survey" class="em-c-
switch__input em-js-switch-trigger" >
</div>
</div>
</div>
</li>
<li class="em-c-switch-list__item">
<div class="em-c-field">
<div class="em-c-field__body">
<div class="em-c-switch">
<label class="em-c-switch__label" for="switch-2">
<span class="em-c-switch__toggle"></span>
<span class="em-c-switch__label-name">Upload Project</span>
</label>
<input id="switch-2" type="checkbox" name="switch-2" value="Project" class="em-c-
switch__input em-js-switch-trigger">
</div>
</div>
</div>
</li>
</ul>
<!-- agregar las botones de survey y project-->
<!--agregar el boton de submit -->
<div class="em-u-text-align-center">
<div class="em-c-btn-group "></div>
<button type="submit" value="submit" class="em-c-btn em-c-btn--primary">
<span class="em-c-btn__text">Submit</span>
</button>
</div>
</form>
<script type="text/javascript" src="../static/js/em-unity-1.6.0.min.js"></script>
</body>
Error I get
"Oracle client has already been initialized"
"'None Type' object has no attribute 'cursor'"
The first error suggests that you are calling cx_Oracle.init_oracle_client() more than one time. You aren't supposed to do that! See the documentation for details. You can perform the initialization directly in your module code, or you can use a global variable to ensure that it is only called once.
The second error suggests that you are trying to create a cursor on a None connection object -- which in turn suggests that your utils.CreateConnection() function is catching exceptions and returning None instead of a valid connection. Avoid catching exceptions unless you have to, and then ensure that you're not just swallowing the exception and causing exceptions elsewhere!

Inserting data into an Oracle database from a form in Python Flask

I have a Python code.
import cx_Oracle
import re
from flask import Flask, render_template, request, url_for, redirect
app = Flask(__name__)
app.config['SECRET_KEY'] = 'd369342136ecd032f8b4a930b6bb2e0e'
#app.route('/add')
def edited():
connect = cx_Oracle.connect("********", "********", "******/XE")
cursor = connect.cursor()
cod_ed = request.form['cod_ed']
nome_ed = request.form['nome_ed']
endereco = request.form['endereco']
telefone = request.form['telefone']
cidade = request.form['cidade']
execute = """INSERT INTO editor VALUES
(:cod_ed, :nome_ed, :endereco, :telefone, :cidade)"""
cursor.execute(execute, {'cod_ed':cod_ed, 'nome_ed':nome_ed, 'endereco':endereco, 'telefone':telefone, 'cidade':cidade})
connect.commit()
#app.route('/', methods=['GET', 'POST'])
def add_data():
return render_template('forms.html')
#app.route('/post_data', methods=['GET','POST'])
def post_data():
return redirect(url_for('edited'))
if __name__ == "__main__":
app.run(host = 'localhost', port = 8000, debug=True)
And its html correspondante:
<!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous">
</script>
<title>Base de dados</title>
</head>
<body>
<form methods="POST" action="/post_data">
<div class="col-lg-2">
<div class="form-group">
<label for="element-1" >Codigo:</label>
<input id="cod_ed" name="cod_ed" type="text" class="form-control" placeholder="Codigo"/>
<label for="element-2" >Nome:</label>
<input id="nome_ed" name="nome_ed" type="text" class="form-control" placeholder="Nome"/>
<label for="element-3" >Endereço:</label>
<input id="endereco" name="endereco" type="text" class="form-control" placeholder="Endereço"/>
<label for="element-4" >Telefone:</label>
<input id="telefone" name="telefone" type="text" class="form-control" placeholder="Telefone"/>
<label for="element-5" >Cidade:</label>
<input id="cidade" name="cidade" type="text" class="form control" placeholder="Cidade"/>
<input class="btn btn-info" type="submit" value="Enter">
</div>
</div>
</div>
</form>
</body>
</html>
I'm relatively new to Flask and Python in general. When I run the forms, they get displayed, but when I try to insert them into the database, I get this:
werkzeug.exceptions.HTTPException.wrap.<locals>.newcls: 400 Bad Request: KeyError: 'cod_ed'
What exactly is causing it and how do I fix it?
When posting to /post_data endpoint the browser recieves a redirection code, and then gets /add without posting any data, provoking a key error.
You are fetching form elements at the wrong place. You should do the database insertion logic inside /post_data and redirect to /add afterwards.
Here you are posting the form data to /post_data and redirect it to /add so the edited function will not be able to access the request object containing the form data. So just change the form action to /add to make it work correctly.

Python requests with login credentials

I am trying to login to a URL & download the content then parse, the URL needs username & password to login.
using below gives below errors:
import requests
url = 'https://test/acx/databaseUsage.jssp?object=all'
values = {'username': 'test_user',
'password': 'test_pswd'}
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
r = requests.post(url, data=values, headers=headers)
print r.content
Error log output from above code:
tried with below values as well , without any success
values = {'Login': 'test',
'Password': 'test',
'Log in': 'submit'}
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge"/> <!-- must be first; see SD5930 -->
<title>Test URL login</title>
<!--meta name="apple-mobile-web-app-capable" content="yes" /-->
<link type="text/css" rel="StyleSheet" href="/nl/logon.css"></link>
</head>
<body onLoad="setFocus();">
<div id="htmlContent">
<div id="container">
<div id="content">
<div class="login_frame">
<div class="header_login">
<img src="/nl/img/logo.png" alt="Test URL" />
</div>
<div id="form-main">
<!--[if lte IE 7]>
<div class="warning"><b>Warning</b>: your browser isn't supported by Test URL. <br/>To be able to use Test URL to its full potential, you need to update your browser.</div>
<![endif]-->
<form method="POST" autocorrect="off" autocapitalize="off" name="loginForm" action="/nl/jsp/logon.jsp">
<input type="hidden" name="action" value="submit" />
<input type="hidden" name="target" value="/acx/databaseUsage.jssp?object=all">
<p class="input first">
<label for="login">Login</label>
<span>
<input id="login" name="login" tabindex="1" type="text" value="" />
</span>
</p>
<p class="input">
<label for="password">Password</label>
<span>
<input id="password" name="password" tabindex="2" type="password" autocomplete="off" />
</span>
<br />
</p>
<p class="memorize submit last">
<input id="rememberMe" name="rememberMe" class="checkbox" tabindex="3" type="checkbox" />
<label class="checkbox" for="rememberMe">Keep me logged in</label>
<button id="validate" type="submit">Log in</button>
</p>
</form>
</div>
</div>
</div>
</div>
<div id="footer" class="dashboardFooter">
<div id="footerContent" class="nlui-pageWidth">
<p>
© Test URL 2017
</p>
</div>
</div>
</div>
<script type="text/javascript">
function setFocus() {
document.loginForm.login.focus();
}
</script>
</body>
</html>
Image of login page
In order to login successfully you'll have to submit the correct data to the correct URL. You can get those values from the HTML form, or by inspecting the network traffic in your browser. Also, you may want to gather any authenticated cookies.
Make sure to use the correct URL. You can get that URL from the form's action attribute (if the form has no action it is submitted to the URL that hosts it). If you examine the form you'll see that it is submitted to: "/nl/jsp/logon.jsp".
Make sure to include all required data. If the form contains hidden inputs they should be included in the POST data. It is important to submit all the form fields because they may contain essential data.
You can use a Session() object to store your cookies. This will collect and use cookies (and other parameters) across requests, and so you can access the site as an authenticated user.
If you want to set or change headers you can use either the headers parameter or the Session.headers attribute - which wil use those headers for all requests. Usually changing the default User-Agent is enough, but some sites may expect more headers (a valid Referer for example).
import requests
url = 'https://example.com/nl/jsp/logon.jsp'
post_data = {
'login': 'username',
'password': 'password',
'target':'/acx/databaseUsage.jssp?object=all',
'action':'submit'
}
with requests.Session() as s:
s.headers['User-Agent'] = 'My user-agent'
r = s.post(url, data=post_data)
print(r.text)
If you still can't login you may have to use Selenium. Sometimes JavaScript is involved in the login process and requests doesn't run JavaScript code. It may be possible to reverse-engineer this process but it would be much easier/better to use Selenium.

python flask render_template html did not render correctly

I'm building a python flask app implementing user log in , after user log in succefully, it will redirect to userHome.html
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Python Flask Bucket List App</title>
    <link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
 
    <link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
    <link href="../static/css/signup.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <div class="header">
            <nav>
                <ul class="nav nav-pills pull-right">
                    <li role="presentation" class="active">Logout
                    </li>
                </ul>
            </nav>
            <h3 class="text-muted">Python Flask App</h3>
        </div>
 
        <div class="jumbotron">
            <h1>Welcome Home !!</h1>  
        </div> 
        <footer class="footer">
            <p>© Company 2015</p>
        </footer>  
    </div>
</body>
</html>
and the python code to perform return render_template('userHome.html')
in validateLogin :
#app.route('/validateLogin',methods=['POST'])
def validateLogin():
cursor = None
try:
_username = request.form['inputName']
_password = request.form['inputPassword']
# connect to mysql
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('sp_validateLogin',(_username,_password))
data = cursor.fetchall()
if len(data) > 0:
return render_template('userHome.html')
else:
return render_template('error.html', error = "Wrong Username or
Password")
except Exception as e:
return render_template('error.html',error = str(e))
finally:
if cursor:
cursor.close()
conn.close()
and the signin.js :
$(function(){
$('#btnSignIn').click( function(){
$.ajax({
url: '/validateLogin',
data: $('form').serialize(),
type: "POST",
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
});
and finally the signin.html:
!DOCTYPE html>
<html lang="en">
<head>
<title>Sign In</title>
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="http://getbootstrap.com/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
<link href="../static/signup.css" rel="stylesheet">
<script src="/static/js/jquery-3.1.1.js"></script>
<!--<script src="/static/js/jquery-3.1.1.min.map"></script>-->
<script src="/static/js/signin.js"></script>
</head>
<body>
<div class="container">
<div class="header">
<nav>
<ul class="nav nav-pills pull-right">
<li role="presentation" >Home</li>
<li role="presentation" class="active">Sign In</li>
<li role="presentation">Sign Up</li>
</ul>
</nav>
<h2 class="text-muted">Release Control System</h2>
</div>
<div class="jumbotron">
<h1>Log In</h1>
<form class="form-signin">
<label for="inputName" class="sr-only">Name</label>
<input type="name" name="inputName" id="inputName" class="form-control" placeholder="Name" required autofocus>
<!--<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" name="inputEmail" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>-->
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="inputPassword" id="inputPassword" class="form-control" placeholder="Password" required>
<button id="btnSignIn" class="btn btn-lg btn-primary btn-block" type="button">Sign in</button>
</form>
</div>
<footer class="footer">
<p>Copyright 2017 Foxconn CABG © All Rights Reserved.</p>
</footer>
</div>
</body>
</html>
but when I log in successfully it does not direct to the userHome.html page, it showed all html entities instead. Meaning the templates are working but the browser is treating wrongly.
I've tried many tricks like:
headers = {'Content-Type': 'text/html'}
return make_response(render_template('userHome.html'),200,headers)
but it still returns html entities, not html page.
This has confused me for days, thanks in advance.
Since I don't know how to send a redirect request to ajax and execute it. I will simply share the way I do things.
# Python Code
#app.route('/login')
def login():
# check if user is not logged in then render the login form
if user_not_logged_in():
return render_template('login_form.html')
# if user logged in, then redirect to userHome
else:
return redirect(url_for('userHome'))
from flask import jsonify
#app.route('/validateLogin', methods=['POST'])
def validateLogin():
# do some stuff and check for validation
if stuff_goes_well:
return jsonify({'data': 'success'})
else:
return jsonify({'data': 'failure'})
#app.route('/userHome')
def userHome():
# check if user is logged in
if logged_in_user_session_exists():
return render_template('userHome.html')
else:
# user is not logged in so redirect him to the login page
return redirect(url_for('login'))
# jQuery code
$.ajax({
url: "/validateLogin",
type: "POST",
dataType: "json",
data: data_here,
success: function(response){
if(response.data == 'success'){
# success was sent so the user logged in successfully, redirect to user home
window.location.replace('/userHome');
}else{
# there was an error in the logging in
alert('there was an error!');
}
}
});
To sum it up in a few words: simply send your data with ajax to Python. then let Python handle verification and the analysis of the data. then if all goes well, tell jQuery " hey it's all cool here " ( which is represented by the 'success' string we send ). if something was wrong then we tell jQuery that we had a problem hence the 'failure' string we send. then in jQuery we act upon the string that was sent. if it was success, then we redirect the user to the desired URL ( which is /userHome in this case ). if failure was sent then we say there was an error.
Please notice that these python checks are important so the user just doesn't type "/userHome" in the URL and be able to just view the page while he is not logged in.
I hope you find this useful.

How to bypass Mechanize "AmbiguityError" in Python

I am trying to upload images to ImageBam by filling its web-forms and requesting POST.
I don't know too much about urllib2, httplib, multipart stuff. I am trying to use MECHANIZE module
But I think it shouldn't be too complex because it is just a web form, I will fill it and post it.
The page, where upload forms are:
http://www.imagebam.com/basic-upload
The form I am trying to fill:
<form name='form' id='form' enctype="multipart/form-data" method="post" action="/sys/upload/save">
<table align="center">
<tr>
<td>
01: <input type="file" name="file[]" size="30"><br>
02: <input type="file" name="file[]" size="30"><br>
03: <input type="file" name="file[]" size="30"><br>
04: <input type="file" name="file[]" size="30"><br>
05: <input type="file" name="file[]" size="30"><br>
also I saw a guy created an app using python;
http://sourceforge.net/projects/pymguploader/files/pymguploader/2011-12-24/
I want to write something like that, but much more basic of course.
anyway, here is my problem;
when I execute these;
import mechanize
a=mechanize.Browser()
a.open("http://www.imagebam.com/basic-upload")
forms=mechanize.ParseResponse(response)
a.select_form(nr=0)
dosya=open("file path...","r")
everything works fine I think.
also
print a
gives this output:
<Browser visiting http://www.imagebam.com/basic-upload
selected form:
<form POST http://www.imagebam.com/sys/upload/save multipart/form-data
<FileControl(file[]=<No files added>)>
<FileControl(file[]=<No files added>)>
<FileControl(file[]=<No files added>)>
<FileControl(file[]=<No files added>)>
<SelectControl(content_type=[*x, 1, 0])>
<SelectControl(thumb_size=[*100, 150, 180, 250, 300, 350])>
<SelectControl(thumb_aspect_ratio=[crop, *resize])>
<SelectControl(thumb_file_type=[gif, *jpg])>
<CheckboxControl(thumb_info=[1])>
<CheckboxControl(gallery_options=[*1])>>
>
but when I
a["file[]"]=dosya
the error is;
Traceback (most recent call last):
File "<pyshell#46>", line 1, in <module>
a["file[]"]=dosya
File "build\bdist.win32\egg\mechanize\_form.py", line 2780, in __setitem__
control = self.find_control(name)
File "build\bdist.win32\egg\mechanize\_form.py", line 3101, in find_control
return self._find_control(name, type, kind, id, label, predicate, nr)
File "build\bdist.win32\egg\mechanize\_form.py", line 3183, in _find_control
raise AmbiguityError("more than one control matching "+description)
AmbiguityError: more than one control matching name 'file[]'
How can I solve this problem?
SOLVED
Solution:
a.add_file(dosya,"filename",nr=0)
that automatically searches type=file inputs and adds my file to first one(nr=0 provides it)
New Problem
After I sending POST data (or I think it sends)
This page comes as a response;
<?xml version='1.0' encoding='utf-8'?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://opengraphprotocol.org/schema/" xmlns:fb="http://developers.facebook.com/schema/" xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="author" content="ImageBam.com" />
<meta name="description" content="Free Image Hosting and photo sharing. Create an online album with bulk upload tools and share with family and friends." />
<meta name="keywords" content="image hosting, free image hosting, photo sharing, upload photo, free photo gallery, photo host, image gallery" />
<meta name="robots" content="follow" />
<meta name="revisit-after" content="1 days" />
<meta property="fb:admins" content="3433880" />
<link rel="stylesheet" href="http://www.imagebam.com/style.css" type="text/css" />
<link rel="shortcut icon" href="http://www.imagebam.com/favicon.ico" />
<title>Fast, Free Image Hosting - ImageBam</title>
<script type="text/javascript" src="http://www.imagebam.com/JS/imagebam.js"></script>
<script type="text/javascript" src="http://www.imagebam.com/JS/pt.js"></script>
</head>
<body>
<!-- IMAGEBAM HEADER -->
<div class="scrollme">
<div class="abody">
<!-- everything -->
<div class="banner cursor" style="float:left;" onclick='top.location="http://www.imagebam.com"'></div>
<div style="float:right; text-align:right; border:0px solid #f2f2f2; border-top:none; padding-top: 5px; padding-left:3px; padding-right:10px;">
</div>
<div style="clear:left;"></div>
<div class="dtab">
<ul>
<li class="inactive">Multi-Upload</li>
<li class="inactive">Zip-Upload</li>
<li class="inactive">Basic Upload</li>
<li class="inactive">Learn More</li>
<li class="inactive">FAQ</li>
<li class="inactive">Register</li>
<li class="inactive">Login</li>
<li class="inactive">Premium</li>
</ul>
</div><br />
<!-- Google Code for Imagebam Uploaded Image Conversion Page -->
<script type="text/javascript">
/* <![CDATA[ */
function img404(ID,fsrc){
document.getElementById('thumb_404_info').style.display="block";
document.getElementById("img_"+ID).style.display = "none";
document.getElementById("alt_"+ID).style.display = "inline";
setTimeout("reloadImg("+ID+",'"+fsrc+"')", 500);
}
function reloadImg(ID,fsrc){
mrand = Math.random();
document.getElementById("img_"+ID).style.display = "inline";
document.getElementById("alt_"+ID).style.display = "none";
document.getElementById("img_"+ID).src = fsrc+"?"+mrand;
}
/* ]]> */
</script>
<div class="box_wait" style="text-align:center; display:none;" id="thumb_404_info">Thumbnails that are being processed in the background might not load right away.<br /></div>
<div style="text-align:center; margin-bottom:5px;">
<b>NEW!</b> VideoBam.com (HD Video Hosting)
</div>
<fieldset><legend><img src="/img/icons/photos.png" alt="" style="vertical-align:middle; line-height:16px; height:16px; padding-right:5px;" /> All at Once</legend>
<table style="width:100%;"><tr>
<td>
<b>BB-Code</b><br />
<textarea onclick="this.select();" style="width:300px; height:200px;"></textarea>
</td>
<td>
<b>HTML-Code</b><br />
<textarea onclick="this.select();" style="width:300px; height:200px;"></textarea>
</td>
</tr>
</table>
</fieldset>
<!--
<fieldset><legend style='color:green;'><img src='/img/icons/new.png' alt='' style='vertical-align:middle; line-height:16px; height:16px; padding-right:5px;'> NEW! ImageBam Remote Upload Widget</legend>
<b>Webmasters / Mods!</b><br> Allow your users to upload images to ImageBam <b>without leaving your website or forum!</b><br> Add our new ImageBam Remote Upload Widget to you website!<br>
Please spread the word! Thank you!
</fieldset>
-->
<div style="text-align:center; margin-bottom:5px;">
<b>NEW!</b> VideoBam.com (HD Video Hosting)
</div>
<fieldset><legend><img src="/img/icons/delete.png" alt="" style="vertical-align:middle; line-height:16px; height:16px; padding-right:5px;" /> All Removal Links</legend>
Do not share the links below. You can use them to delete the photos you have uploaded.<br />
<textarea onclick="this.select()" style="width:600px; height:200px;"></textarea>
</fieldset>
<!-- Google Code for Imagebam Uploaded Image Conversion Page -->
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = 1068053810;
var google_conversion_language = "en_US";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "6tqpCPa-chCy6qT9Aw";
var google_conversion_value = 0;
/* ]]> */
</script>
<script type="text/javascript" src="http://www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/1068053810/?label=6tqpCPa-chCy6qT9Aw&guid=ON&script=0" />
</div>
</noscript>
</div>
<div class="footer">
<a class="footera" href="http://www.imagebam.com/">ImageBam</a> | <a class="footera" href="/remote-upload-widget">Remote Upload Widget</a> | <a class="footera" href="http://www.imagebam.com/screengrab_upload_firefox_extension">screengrab tool</a> | <a class="footera" href="http://www.imagebam.com/terms-of-service">terms of service</a> | <a class="footera" href="http://www.imagebam.com/frequently-asked-questions">help</a> | <a class="footera" href="http://support.imagebam.com" target="_blank">support forums</a> | <a class="footera" href="http://code.google.com/p/imagebam-api/">API for developers</a> | <a class="footera" href="http://www.imagebam.com/report-abuse">report abuse</a>
<div style="height:35px; overflow:hidden;">
<div id="google_translate_element" style="margin-top:9px;"></div><script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({
pageLanguage: 'en'
}, 'google_translate_element');
}
</script><script src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit" type="text/javascript"></script>
</div>
<div style="text-align:center; color:#999; margin-top:10px;">
<table style="margin:auto;"><tr><td><img src="http://1.imagebam.com/static/img/tux.png" alt="tux" /></td><td>Powered by dedicated Linux servers. Flixya Entertainment, LLC © 2010</td></tr></table>
</div>
</div>
</div>
<div id="updater_index"></div>
<script type="text/javascript">
</script>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2424497-2";
urchinTracker();
</script>
</body>
</html>
Normally, it is the after-uploading page that comes out with image's links etc.
But I think there is a dynamic process, because the links were not prepared when I got the page.
Am I missing something? because even if you dont fill the inputs on form, if you submit() it, it redirects you to that after-uploading page..
Use select_control() also with nr=0 to select the first file.

Categories

Resources