Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Menu
Open sidebar
micropython-public
micropython-helper-scripts
Commits
ed5153df
Commit
ed5153df
authored
Nov 19, 2019
by
Klint Youngmeyer
Browse files
Add basic webserver example. Only works with for small files at this point. Still a WIP
parent
83cc1980
Changes
1
Hide whitespace changes
Inline
Side-by-side
basic_webserver.py
0 → 100644
View file @
ed5153df
import
pyb
import
network
import
socket
# nic = network.RS911X(pyb.SPI(2), pyb.Pin("I0"), pyb.Pin("E3"), pyb.Pin("E4"))
# nic.connect('ASUS_E8_2G', '3197597781')
def
webserver
(
nic
):
allowed_errors
=
[
105
]
HOST
,
PORT
=
nic
.
ifconfig
()[
0
],
8082
print
(
"Simple Webserver Running at: {}:{}"
.
format
(
HOST
,
PORT
))
my_socket
=
socket
.
socket
(
socket
.
AF_INET
,
socket
.
SOCK_STREAM
)
my_socket
.
bind
((
HOST
,
PORT
))
my_socket
.
listen
(
1
)
while
True
:
attempts
=
0
connection
=
None
address
=
None
while
attempts
<
3
:
try
:
connection
,
address
=
my_socket
.
accept
()
break
except
OSError
as
e
:
attempts
+=
1
if
e
.
args
[
0
]
not
in
allowed_errors
:
print
(
"OS Error: {}"
.
format
(
e
))
pyb
.
delay
(
10
)
request
=
connection
.
recv
(
1024
).
decode
(
'utf-8'
)
string_list
=
request
.
split
(
' '
)
method
=
string_list
[
0
]
requesting_file
=
string_list
[
1
]
try
:
myfile
,
data
=
requesting_file
.
split
(
'?'
)
except
ValueError
:
myfile
=
requesting_file
.
split
(
'?'
)[
0
]
data
=
None
myfile
=
myfile
.
lstrip
(
'/'
)
if
(
myfile
==
'/'
):
myfile
=
'index.html'
try
:
file
=
open
(
myfile
,
'rb'
)
response
=
file
.
read
()
file
.
close
()
header
=
'HTTP/1.1 200 OK
\n
'
if
(
myfile
.
endswith
(
".jpg"
)):
mimetype
=
'image/jpg'
elif
(
myfile
.
endswith
(
".css"
)):
mimetype
=
'text/css'
else
:
mimetype
=
'text/html'
header
+=
'Content-Type: '
+
str
(
mimetype
)
+
'
\n\n
'
except
Exception
:
header
=
'HTTP/1.1 404 Not Found
\n\n
'
response
=
'<html><body><center><h3>Error 404: File not found</h3><p>Python HTTP Server</p></center></body></html>'
.
encode
(
'utf-8'
)
final_response
=
header
.
encode
(
'utf-8'
)
final_response
+=
response
connection
.
send
(
final_response
)
#connection.close()
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment