I am allergic to penicillin is it safe to take cephalexin for infection in the urine.

Yes. Unless you had an anaphylactic reaction to penicillin (major breathing problems) there is little risk to trying cephalexin.
Probably should not. Cephalexin is related to penicillin and there is a chance of an allergic reaction. Many people who are allergic to penicillin can take Cephalexin safely, but i would not suggest it.