How to create a html page after user sign up? - python

I am working with a chat web app. In the chat app, the user will create a his account and then, the server will do the following process (all the process will be done using post request in my whole application):-
Save the credentials in a txt file
Create a html homepage for the user
Send a success message
The code for the server is:-
elif 'signup%20name?=' and "%20pwd?=" in self.path:
users = open("users.txt", 'a+')
usr = (self.path).replace("/signinupsignup%20name?=", '')
usrpw = usr.replace("%20pwd?=", "<[-----=-----]>")
usrpwd = usrpw + '\n'
users.write(usrpwd)
users.close()
filenam = usrpw.replace('<[-----=-----]>', '')
filename = '/userhome/' + filenam + '.html'
htmlfile = open(filename, 'w')
htmlfile.write(r'<!DOCTYPE html>\n<html lang="en">\n<head>\nmeta charset="UTF-8">\n<meta name="viewport" content="width=device-width, initial-scale=1.0">\n<title>User Home</title>\n<style>\n#navbar\n{\nbackground-color: purple;\ncolor: white;\ntext-align: center;\nposition: relative;\n}\n#chats a:hover\n{\ncolor: white;\nbackground-color: black;\n}\n</style>\n</head>\n<body>\n<div id="navbar">\n<div id="welcome">\n<h1>Cobra Chat-Room</h1>\n</div>\n</div>\n<div id="chats">\n<!-- chats of the user -->\nGroup 1<br>\<noscript></noscript>\n</body>\n</html>\n')
self.path = '/success.html'
But when I run the file I get the following error:-
Exception occurred during processing of request from ('127.0.0.1', 41192)
Traceback (most recent call last):
File "/usr/lib/python3.9/socketserver.py", line 316, in _handle_request_noblock
self.process_request(request, client_address)
File "/usr/lib/python3.9/socketserver.py", line 347, in process_request
self.finish_request(request, client_address)
File "/usr/lib/python3.9/socketserver.py", line 360, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python3.9/socketserver.py", line 720, in __init__
self.handle()
File "/usr/lib/python3.9/http/server.py", line 427, in handle
self.handle_one_request()
File "/usr/lib/python3.9/http/server.py", line 415, in handle_one_request
method()
File "/home/kali/Desktop/SignUp/server.py", line 16, in do_GET
htmlfile = open(filename, 'w')
FileNotFoundError: [Errno 2] No such file or directory: '/userhome/ssss.html'
----------------------------------------
The filename of the html home-page will be <username><password> without any space. It will be stored in the directory named as "userhome"
(OS => Kali Linux; Pyhton version 3.9)

its may be because the ip address you have given might be wrong
or check whether server is having a static ip
if not it might be changing

Related

Python BaseHTTPServer calls Finish() before I'm done writing to the wfile output stream

I'm trying to serve large files in response to an HTTP GET request with a Python web server. I've overridden do_GET(self) successfully and everything works great for sending small zip files but with larger files I only write around 137MB into the wfile output stream before I get a broken pipe error as BaseHTTPServer is calling finish before I'm done writing.
self.send_header("Content-Type", "application/octet-stream")
self.end_headers()
f = open(filename, 'rb')
fullyWritten = False
count = 0
while not fullyWritten:
tmp = f.read(32768)
count = count + len(tmp)
print count # always a different number before crash
if not tmp:
fullyWritten = True
else:
self.wfile.write(tmp) # never finishes writing large files
print "wrote to http body"
...
...
wrote to http body
137134080
wrote to http body
137166848
wrote to http body
137199616
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 43644)
Traceback (most recent call last):
File "/usr/lib/python2.7/SocketServer.py", line 295, in _handle_request_noblock
self.process_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 321, in process_request
self.finish_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python2.7/SocketServer.py", line 651, in __init__
self.finish()
File "/usr/lib/python2.7/SocketServer.py", line 710, in finish
self.wfile.close()
File "/usr/lib/python2.7/socket.py", line 279, in close
self.flush()
File "/usr/lib/python2.7/socket.py", line 303, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe
----------------------------------------
GO code that's calling the end point:
res, err := http.Get(remoteUri)
if err != nil {
return err
}
defer res.Body.Close()
bodyBytesBuffer := new(bytes.Buffer)
_, err = io.Copy(bodyBytesBuffer, res.Body)
if err != nil {
return err
}
urlReader := bytes.NewReader(bodyBytesBuffer.Bytes())
var zipReader *zip.Reader
zipReader, err = zip.NewReader(urlReader, int64(urlReader.Len()))

error 501 on ftp.retrbinary (ftplib)

I'm coding a script to check a FTP directory and download the new files. This is part of the code:
from ftplib import FTP
import os
ftp = FTP(ftp_lance)
ftp.login(login, password)
ftp.cwd('xxxxxx')
FTP_list = ftp.nlst()
lista_diferenca = [file for file in FTP_list if file not in local_list]
for file in lista_diferenca:
local_filename = os.path.join(cache, file)
ftp.retrbinary('REST ' + file, open(local_filename, 'wb').write)
When I run it, I get this error message:
Traceback (most recent call last):
File "D:\Scripts\Istari\Radagast\Radagast.py", line 44, in <module>
ftp.retrbinary('REST tabela14_pag5.pdf', open(local_filename, 'wb').write)
File "D:\Portable Python 2.7.6.1\App\lib\ftplib.py", line 414, in retrbinary
conn = self.transfercmd(cmd, rest)
File "D:\Portable Python 2.7.6.1\App\lib\ftplib.py", line 376, in transfercmd
return self.ntransfercmd(cmd, rest)[0]
File "D:\Portable Python 2.7.6.1\App\lib\ftplib.py", line 339, in ntransfercmd
resp = self.sendcmd(cmd)
File "D:\Portable Python 2.7.6.1\App\lib\ftplib.py", line 249, in sendcmd
return self.getresp()
File "D:\Portable Python 2.7.6.1\App\lib\ftplib.py", line 224, in getresp
raise error_perm, resp
error_perm: 501 Bad parameter. Numeric value required
I check several sites searching for this kind of error and find nothing. It seems that my retrbinaty is broken, but the arguments looks right (first the 'Rest' + file, and then the callback function).
Some idea about my error?
You need to specify the FTP command RETR, not REST:
ftp.retrbinary('RETR ' + file, open(local_filename, 'wb').write)

Python FTP download not working

I am trying to download a file from FTP using python. I was able to successfully move into the directory but can't download the file.
The command I use is ftp.retrbinary('master.idx', open(fname,'wb').write)
And error is below. It looks like the command is looking for MASTER.IDX instead of master.idx
The full path to the file I want to download is ftp://ftp.sec.gov/edgar/full-index/2011/QTR2/master.idx
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/ftplib.py", line 406, in retrbinary
conn = self.transfercmd(cmd, rest)
File "/usr/lib/python2.7/ftplib.py", line 368, in transfercmd
return self.ntransfercmd(cmd, rest)[0]
File "/usr/lib/python2.7/ftplib.py", line 331, in ntransfercmd
resp = self.sendcmd(cmd)
File "/usr/lib/python2.7/ftplib.py", line 244, in sendcmd
return self.getresp()
File "/usr/lib/python2.7/ftplib.py", line 219, in getresp
raise error_perm, resp
ftplib.error_perm: 500 MASTER.IDX not understood
I can't say why the name changes to uppercase. In any case, when using FTP, I make like this, it may help you:
server = "URL.of.server"
directory = "directory/where/the/file/is"
filename = "nameoffile.txt"
from ftplib import FTP
ftp = FTP(server) #Set server address
ftp.login() # Connect to server
ftp.cwd(directory) # Move to the desired folder in server
ftp.retrbinary('RETR ' + filename,open(filename, 'wb').write) # Download file from server
ftp.close() # Close connection
I think that it may be the 'RETR ', if you don't write, it the server may not understand what you want to do
use wget module of python instead. Here is an example snippet
import wget
fileloc = '/path/to/the/file/foo.txt'
wget.download(fileloc)

Broken pipe during stream

I have a project with Django I am working on where I want to stream some mp3 files.
I have this same issue:
Streaming mp3 files with django, read from a page with <audio>
Let me explain: I want stream an ogg with Django, and with an <audio> tag in my html page
I have a url like domain.tld/song/show/X/, where X is the id of my song.
I can stream with VLC (directly with the file path), I can stream during test, (I write what I receive and read it with VLC).
But when I open my browser and load my home page domain.tld where I have and <\audio\> balise with url domain.tld/song/show/1/, I get a big broken pipe, as if my client closed the connection.
I read on others post that some problems was resolved when they put server in production. So I push my app on server, use apache, with the django.wgsi like on djangoproject.com.
I am running python 2.7.3 on Debian 7 with Django version 1.5.
there my code:
Song/views.py
def playAudioFile(request, pk):
f = get_stream_song(pk)# return a pipe from pipes.Template
l = f.read() # the file is an ogg get by pydub.com
f.close()
size_read = 550000
sr = size_read
while sr == size_read:
print "rep"
r = l[:size_read]
l=l[size_read:]
sr = len(r)
yield r
time.sleep(0.1)
#url : ~/song/show/X/
##login_required
def show_song(request, pk):
return StreamingHttpResponse(playAudioFile(request, pk), mimetype='audio/ogg',)
In my HTML, I just have that:
<audio controls height="100" width="100" preload="auto">
<source src="/.../song/show/1/" type="audio/ogg">
<embed height="50" width="100" src="/.../song/show/1/">
</audio>
The error looks like:
Traceback (most recent call last):
File "/usr/lib/python2.7/wsgiref/handlers.py", line 86, in run
self.finish_response()
File "/usr/lib/python2.7/wsgiref/handlers.py", line 127, in finish_response
self.write(data)
File "/usr/lib/python2.7/wsgiref/handlers.py", line 215, in write
self._write(data)
File "/usr/lib/python2.7/socket.py", line 324, in write
self.flush()
File "/usr/lib/python2.7/socket.py", line 303, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 104] Connection reset by peer
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 46392)
Traceback (most recent call last):
File "/usr/lib/python2.7/SocketServer.py", line 593, in process_request_thread
self.finish_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/home/lumy/SPhoque/SonoPhoque/SoPhoque/local/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 150, in __init__
super(WSGIRequestHandler, self).__init__(*args, **kwargs)
File "/usr/lib/python2.7/SocketServer.py", line 651, in __init__
self.finish()
File "/usr/lib/python2.7/SocketServer.py", line 704, in finish
self.wfile.flush()
File "/usr/lib/python2.7/socket.py", line 303, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe
I got this twice each time I try to stream.
Edit 15h 29/05:
I did what rahan suggested:
Looking at Firebug and Firefox debugger:
The client does:
GET 1 200 OK localhost:8000 537.1KB 4.71s
Headers
Response Headersview source
Date Wed, 29 May 2013 13:08:54 GMT
Server WSGIServer/0.1 Python/2.7.3
Content-Type audio/ogg
Request Headersview source
Host localhost:8000
User-Agent Mozilla/5.0 (X11; Linux x86_64; rv:10.0.12) Gecko/20100101 Firefox/10.0.12 Iceweasel/10.0.12
Accept audio/webm,audio/ogg,audio/wav,audio/*;q=0.9,application/ogg;q=0.7,video/*;q=0.6,*/*;q=0.5
Accept-Language en-us,en;q=0.5
Connection keep-alive
Range bytes=0-
Referer http://localhost:8000/
and details say that the total size for all documents is 1 MB (526 KB from cache)
May be I am crossing your existing solution, i have a suggestion, for mp3 streaming use nginx/apache server, these days there is solution known as sendfile, for example in your case on django view
def send_file_header(server_type):
header = "X-Sendfile" if server_type == "apache" else "X-Accel-Redirect"
return header
#login_required
def show_song(request, pk):
res = HttpResponse()
path = "/path/to/secret/x.mp3"
response[send_file_header('nginx')] = path
response['Content-Type']= "application/octet-stream"
response['Content-Disposition'] = "attachment; filename=\"x.mp3\""
return response

'put' in SFTP using Paramiko

I've installed and written the following Paramiko which is unable to put the file. It is easily able to 'get' a file and execute ls commands on it.
#set username & password
username='runaway'
password='runaway'
port=22
source= '/Unzip.sh'
destination ='/var/mpx/www/http'
#SFTP
client.load_system_host_keys()
print " hostname =%s \n username=%s \n password=%s \n" (hostname,username,password)
t = paramiko.Transport((hostname, port))
t.connect(username=username,password=password)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put(source,destination)
#sftp.close()
#t.close()
Using a 'put' command gives the following error & stack trace -
File "upload_file.py", line 84, in ?
sftp.put(source,destination)
File "/usr/lib/python2.4/site-packages/paramiko/sftp_client.py", line 522, in put
fr = self.file(remotepath, 'wb')
File "/usr/lib/python2.4/site-packages/paramiko/sftp_client.py", line 221, in open
t, msg = self._request(CMD_OPEN, filename, imode, attrblock)
File "/usr/lib/python2.4/site-packages/paramiko/sftp_client.py", line 572, in _request
return self._read_response(num)
File "/usr/lib/python2.4/site-packages/paramiko/sftp_client.py", line 619, in _read_response
self._convert_status(msg)
File "/usr/lib/python2.4/site-packages/paramiko/sftp_client.py", line 649, in _convert_status
raise IOError(text)
IOError: Failure
How do I overcome this?
The solution seemed very funny to me!
source= '/Unzip.sh'
destination ='/var/mpx/www/http/Unzip.sh'
Just modified the destination path to include the file name as well.
Didn't expect some error like this coming from a Python package.
This also occurs in 2.0.2 when you try to sftp.mkdir('/exists'):
Traceback (most recent call last):
...
File "/usr/local/lib/python2.7/site-packages/paramiko/sftp_client.py", line 380, in mkdir
self._request(CMD_MKDIR, path, attr)
File "/usr/local/lib/python2.7/site-packages/paramiko/sftp_client.py", line 730, in _request
return self._read_response(num)
File "/usr/local/lib/python2.7/site-packages/paramiko/sftp_client.py", line 781, in _read_response
self._convert_status(msg)
File "/usr/local/lib/python2.7/site-packages/paramiko/sftp_client.py", line 811, in _convert_status
raise IOError(text)
IOError: Failure
This was my Python 2.7.9 fix:
try:
sftp.mkdir(remote_dir)
except IOError:
logging.debug('%s already exists.', remote_dir)

Categories